Hi i need a javascript regex for a name field in my html form. The user should be able to enter multiple names seperated with space. And first character of all names should be a capital. No numbers, special chars. etc.
thank you.
Hi i need a javascript regex for a name field in my html form. The user should be able to enter multiple names seperated with space. And first character of all names should be a capital. No numbers, special chars. etc.
thank you.
^[A-Z][a-zA-Z]* [A-Z][a-zA-Z]*$
if need more than two names:
^([A-Z][a-zA-Z]*)( [A-Z][a-zA-Z]*)*$
^([A-Z][a-z]* [A-Z][a-z]*)*
will match the following strings and capture them into groups like so:
Tyler Durden something else John Doe another thing Barack Obama
Tyler Durden
John Doe
Barack Obama
^([A-Z][a-z]* [A-Z][a-z]*)(:b+[A-Z][a-z]* [A-Z][a-z]*)*$
You can use more than one space to separate each name. This is if you interpret being able to give "multiple names" as meaning a single name is a combination of the first and the last name.
This should match multiple names like this:
Bill Smith
or
Bill Smith Brian Jones Allan King
\b([A-Z][a-z]* [A-Z][a-z]*)\b
\b
matches a word boundarym with 0 width.
var nameOne = "Tyler Durden";
nameOne.match(/^[A-Z][a-zA-Z]*(\s+[A-Z][a-zA-Z]*)*$/);
>>> [ "Tyler Durden", " Durden" ]
var nameTwo = "Tyler Francis Durden";
nameTwo.match(/^[A-Z][a-zA-Z]*(\s+[A-Z][a-zA-Z]*)*$/);
>>> ["Tyler Francis Durden", " Durden"]
Because of the parenthesis defining a capturing group you get the final name as a captured match. To get the whole name if it matches, use
nameTwo.match(/^[A-Z][a-zA-Z]*(\s+[A-Z][a-zA-Z]*)*$/)[0];
>>> "Tyler Francis Durden"
If you only care about matched vs unmatched, you can just test the return for null