0

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 :)

2 Answers 2

2

if($name==""){ $text = " Error ! field must not be empty "; return $text; }

    if(!preg_match("/^[a-zA-Z'-]+$/", $name)){
    echo '<h4 class="error">Name is not valid! It must not contain numbers   or special characters </h4>.</a>';
    exit;
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Some additional explanations about this code only answer would probably be beneficial.
What question are you answering?
1

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

1 Comment

Escape character is backslash not forward slash. Why using octal \040 instead of simple space?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.