Question

How do I validate the first name to only contain a-z characters using php. I have the following at the moment:

 if (empty($myFirstName)) {
    echo "<p>Please enter your first name!</p>";
else if(!preg_match("/^[a-zA-Z]$/", $myFirstName)){
    echo "Your first name can only contain letters!";
}
Was it helpful?

Solution

Here's a working code :

if (empty($myFirstName)) {
    echo "<p>Please enter your first name!</p>";}

else if(preg_match("/[^a-zA-Z]/", $myFirstName)){
    echo "Your first name can only contain letters!";
}

I did a little modification to the regex : I added a ^ in the group, and removed the anchors.

As a result, your regex will match any character which is not a letter, and display the error message if there is a match.

I strongly advice you to validate user input at least on server side, and on client side if you want to.

For an email validation, the html filter works on client side.

On server side, you can use pre-set PHP filters :

if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo "email OK";
}

FYI, there is a regexp matching emails according to the RFC2822 standards :

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

OTHER TIPS

May be you can use

if(! ctype_alpha($myFirstName) )
{
  //check for alphabetic inputs only
  echo "Your first name can only contain letters!";
}

Php manual

Your if is incorrect.

!preg_match("/^[a-zA-Z]$/", $myFirstName)

will only hold true if $myFirstName is not a single alpha character

to ensure that $myFirstName is not any number of alpha characters, try

!preg_match("/^[a-zA-Z]*$/", $myFirstName)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top