Search code examples
phphtmlformsvalidationpreg-match

Php full name validation?


I need help with my php form validation. I want to validate the full name of a person. I have something like this:

if(!preg_match("/^[a-zA-Z'-]+$/", $name)){
    echo '<h4 class="error">Name is not valid! It must not contain numbers   or special characters. <br> No letters or special characters allowed!</h4><a href="contact.php" class="button block">Go back and try again.</a>';
exit;
}

So far it works fine with reporting error if I write something like John* or Jo7hn or whatever. It works if I write Ivan-Ivan. The problem is if I write space in any way it reports me the error. So how can I make it so that I can write full name with space without getting an error but still forbidd numbers and special characters? I feel like im missing something in that preg_match function but can't find it.

Thanks a lot :)


Solution

  • Try this:

    if(!preg_match("/^[a-zA-Z/'/-\040]+$/", $name)){ ...
    

    \040 is the space you want :)

    PHP Escape sequences

    I create a simple fiddle for you:

    the fiddle