views:

126

answers:

5

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.

+2  A: 
^[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]*)*$
Bick
This only matches two names. OP needs multiple names.
JoshD
Multiple names need to be separated by a space. Marking with spaces would be more appropriate.
Stefan Kendall
Thank you) updated
Bick
And what about names in non-Latin alphabets, or ones containing apostrophes (e.g. O'Relly)
vstoyanov
^([A-ZА-Я]['a-zа-яA-ZА-Я]*)( [A-ZА-Я]['a-zа-яA-ZА-Я]*)*$ ?)
Bick
A: 

^([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

Aphex
"123Tyler Durden123" will pass this regex. Use ^ and $
Bick
You're right, fixed.
Aphex
A: 
^([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

adymitruk
"Tyler Durden" dont match this regex..
Bick
editor was eating my characters before.. added the code section
adymitruk
+1  A: 
\b([A-Z][a-z]* [A-Z][a-z]*)\b

\b matches a word boundarym with 0 width.

Stefan Kendall
A: 
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

Stephen P