0

I have a problem of a single input that has to have two names of a person input. Validating the name input to be of letters worked okay like it is shown here:

if(!preg_match("/^[a-zA-Z'-]+$/", $_POST['name'] )){
  echo 'name must be letters';
}

That will only validate a single name eg: John. But what I need is to validate the that the string contains two words. Like James Doe

This is the form input:

<input autofocus id="aum" name="name" placeholder="John Doe" type="text" />
1
  • Do you want to only allow exactly two words? Commented Sep 21, 2018 at 20:15

2 Answers 2

3

You can use the following regular expression:

^[a-zA-Z'-]+ [a-zA-Z'-]+$

Keep in mind, that you are disallowing every other character (e.g. foreign languages). Therefore it is better to use any possible word character. For PHP this would be \p{L}

^\p{L}+ \p{L}+$

You can also use multiple spaces (^\p{L}+ +\p{L}+$) or multiple spaces of any type of whitespace:

^\p{L}+\s+\p{L}+$

Here is a live example: https://regex101.com/r/aUkUKa/2

Sign up to request clarification or add additional context in comments.

1 Comment

good elaboration and my problem is solved in a more advanced way. Thanks
0

You can use the meta-character \s which match any whitespace character

/^[a-zA-Z]+\s[a-zA-Z]+$

^\w+\s\w+$

1 Comment

my friend your answer is also okay. Thanks

Your Answer

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