12

I'm validating my contact form using PHP and I've used the following code:

if (ctype_alpha($name) === false) {
            $errors[] = 'Name must only contain letters!';
}

This code is works fine, but it over validates and doesn't allow spaces. I've tried ctype_alpha_s and that comes up with a fatal error.

Any help would be greatly appreciated

2
  • What about hyphens and single quotes/backticks. Those are valid characters in names as well. Commented Mar 11, 2013 at 18:56
  • and what about John O'Reily or Björk Guðmundsdóttir or A'ishah-Yunus Commented Mar 11, 2013 at 19:18

4 Answers 4

33

Regex is overkill and will perform worse for such a simple task, consider using native string functions:

if (ctype_alpha(str_replace(' ', '', $name)) === false) {
  $errors[] = 'Name must contain letters and spaces only';
}

This will strip spaces prior to running the alpha check. If tabs and new lines are an issue you could consider using this instead:

str_replace(array("\n", "\t", ' '), '', $name);
Sign up to request clarification or add additional context in comments.

Comments

12

ctype_alpha only checks for the letters [A-Za-z]

If you want to use it for your purpose, first u will have to remove the spaces from your string and then apply ctype_alpha.

But I would go for preg_match to check for validation. You can do something like this.

if ( !preg_match ("/^[a-zA-Z\s]+$/",$name)) {
   $errors[] = "Name must only contain letters!";
} 

Comments

6

One for the UTF-8 world that will match spaces and letters from any language.

if (!preg_match('/^[\p{L} ]+$/u', $name)){
  $errors[] = 'Name must contain letters and spaces only!';
}

Explanation:

  • [] => character class definition
  • p{L} => matches any kind of letter character from any language
  • Space after the p{L} => matches spaces
  • + => Quantifier — matches between one to unlimited times (greedy)
  • /u => Unicode modifier. Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters

This will also match names like Björk Guðmundsdóttir as noted in a comment by Anthony Hatzopoulos above.

Comments

1
if (ctype_alpha(str_replace(' ', '', $name)) === false)  {
  $errors[] = 'Name must contain letters and spaces only';
}

1 Comment

Welcome to Stack Overflow! While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.