Preg_match for name in php

Home  »  How To Guides  »  PHP   »   How to Validate First and Last Name using Regular Expression in PHP

When you allow the user to submit data on the server, it’s a good idea to validate data before further processing. A name field is a common form filed for a web application. Here we will show how you can validate the name filed to check whether the user provides their first and last name.

The Regular Expression (REGEX) is the easiest way to validate full name format in PHP. You can easily validate first and last name using regular expression in PHP. Use PHP preg_match() function to perform a regular expression match.

The following example code uses preg_match() function and simple REGEX for name validation in PHP.

preg_match("/^([a-zA-Z' ]+)$/","Given_Name");

Usage:

<?php
if(preg_match("/^([a-zA-Z' ]+)$/",$givenName)){
    echo 
'Valid name given.';
}else{
    echo 
'Invalid name given.';
}

I am having difficulties with my php code which validates the form on the page itself before sending out to my email.

This is my PHP which is above the doctype html

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subjectTitle = $_POST['subjectTitle'];
$comment = $_POST['comment'];   
$errormsg = "Invalid Entry";
$validmsg = "Thank you for your message";

if($_POST['submit']) {  
    if(empty($_POST['name'])) {     
        $nameError = true;  
    } 
    if(empty($_POST['email'])) {        
        $emailError = true; 
    }       
    if(empty($_POST['subjectTitle'])) {     
        $subjectError = true;   
    }       
    if(empty($_POST['comment'])) {
        $commentError = true;   
    } 
    else if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['subjectTitle']) || empty($_POST['comment'])) {    
        $error = true;      
    }               
    else {          
        $to = "EMAIL_ADD_GOES_HERE";        
        $name = trim($_POST['name']);
        $email = trim($_POST['email']);
        $subjectTitle = trim($_POST['subjectTitle']);
        $comment = trim($_POST['comment']);         
        $subject = "Contact Form Enquiry";          
        $messages = "\r\n Name: $name \r\n Email: $email \r\n Subject: $subjectTitle \r\n Comments: $comment";
        $headers = "From:" . $name;
        $mailsent = mail($to, $subject, $messages, $headers);       
        if($mailsent) {         
            $sent = true;   
            $name = "";        
            $email = "";
            $subjectTitle = "";
            $comment = "";                          
        }           
    }   
}
?>

and for my HTML , to make viewing easier, I'll just put in the form part.

<html>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
     Name: <input type="text" name="name" id="name" value="<?php echo $name; ?>"> 
     <?php if($nameError == true) {echo $errormsg;} ?>

     Email: <input type="text" name="email" id="email" value="<?php echo $email; ?>"> 
     <?php if($emailError == true) {echo $errormsg;} ?>

     Subject: <input type="text" name="subjectTitle" id="subjectTitle" value="<?php echo $subjectTitle; ?>"> 
     <?php if($subjectError == true) {echo $errormsg;} ?>

     Comments: <textarea name="comment" id="comment"><?php echo $comment; ?></textarea>
     <?php if($commentError == true) {echo $errormsg;} ?>
</form>
</html>

There is no other php code in my html other than stated above.

This validation only works if any field is left empty. It will prompt the error msg within the page itself and would NOT send in the email, which is how it should work..

However, I am facing a weird problem which I can't seem to find out the reason/theory/logic behind it. If u look at the php code, if I didn't have that else if statement

else if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['subjectTitle']) || empty($_POST['comment'])) {        
    $error = true; 
}

the validation fails and will still send in an email when the user keys in the textarea. For example, if the user doesn't fill in the Name, Email and Subject but only the Comments, it will still get sent. However, once i put that else if statement, it fixes the problem.

But the main problem is, preg_match. I want the name fields to allow only space and letters and I want email field to only allow emails. So when I tried to put this code in,

if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
     $nameError = true;
}

or by combing it with the name empty field check

if (empty($_POST['name']) || (!preg_match("/^[a-zA-Z ]*$/",$name))) {
    $nameError = true;      
} 

it doesn't validate correctly. What it does is that, when a user enters a number into the name field and also fills up everything else, it will display error message and also the thank you message and send it to the email, which is not how it should work.

So can I have guidance on how to correct the problem? Is my coding done wrongly and also I would like to know why that else if statement which I have in php makes no sense yet I need that to get the proper validation.

Thank you so much for reading, been stuck on this for the past 6 days and I really dont know how to fix this. Please help me.

Cheers

How can I validate a name in PHP?

PHP validates the data at the server-side, which is submitted by HTML form. You need to validate a few things: Empty String..
$name = $_POST ["Name"];.
if (! preg_match ("/^[a-zA-z]*$/", $name) ) {.
$ErrMsg = "Only alphabets and whitespace are allowed.";.
echo $ErrMsg;.
} else {.
echo $name;.

What does Preg_match mean in PHP?

preg_match() in PHP – this function is used to perform pattern matching in PHP on a string. It returns true if a match is found and false if a match is not found. preg_split() in PHP – this function is used to perform a pattern match on a string and then split the results into a numeric array.

What value is return by Preg_match?

Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

What does Preg_match_all return?

The preg_match_all() function returns the number of matches of a pattern that were found in a string and populates a variable with the matches that were found.