Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex: test people's name

From this questions : javascript regex : only english letters allowed

How can I make that expression test for people's name? Currently it doesn't allow spaces between names at all. I need to be able to match something like John Doe

Cheers

like image 453
yoda Avatar asked Jun 19 '10 00:06

yoda


4 Answers

let result = /^[a-zA-Z ]+$/.test( 'John Doe');
console.log(result);

Throw any symbols you need in the character class. This is why I said be specific about exactly what you want to validate. This regex will not account for accented characters, if you care about that you'd most likely better go with unicode matching.

like image 101
meder omuraliev Avatar answered Nov 02 '22 06:11

meder omuraliev


Try this:

/^(([A-Za-z]+[\-\']?)*([A-Za-z]+)?\s)+([A-Za-z]+[\-\']?)*([A-Za-z]+)?$/

It expects optionally [at least 1 alphabetical character followed by a ' or -] an indefinite number of times. There must be at least one alphabetical character before a required space to ensure we are getting at least the first and last name. This entire pattern is grouped to accept indefinite repetition (for people who like to use all their names, such as John Jacob Jingleheimer Schmidt), but must appear at least once, by means of the + sign right in the middle. Finally, the last name is treated the same way as the other names, but no trailing space is allowed. (Unfortunately this means we are violating DRY a little bit.)

Here is the outcome on several possible pieces of input:

"Jon Doe": true
"Jonathan Taylor Thomas": true
"Julia Louis-Dreyfus": true
"Jean-Paul Sartre": true
"Pat O'Brien": true
"Þór Eldon": false
"Marcus Wells-O'Shaugnessy": true
"Stephen Wells-O'Shaugnessy Marcus": true
"This-Is-A-Crazy-Name Jones": true
"---- --------": false
"'''' ''''''''": false
"'-'- -'-'-'-'": false
"a-'- b'-'-'-'": false
"'-'c -'-'-'-d": false
"e-'f g'-'-'-h": false
"'ij- -klmnop'": false

Note it still doesn't handle Unicode characters, but it could possibly be expanded to include those if needed.

like image 41
Stephen Wylie Avatar answered Nov 02 '22 08:11

Stephen Wylie


^\s*([A-Za-z]{1,}([\.,] |[-']| ))+[A-Za-z]+\.?\s*$

Similar as @Stephen_Wylie's solution, but shorter (better?).

like image 40
user2340939 Avatar answered Nov 02 '22 08:11

user2340939


FWIW, I wrote this regex for cleaning up names:

let name = "John Doe";
let result = name.replace(/[^A-Za-z0-9_'-]/gi, '');
console.log(result);

This will let names like O'Brien, Smith, Smith-O'Brian pass through, but will prevent "names" like Engle;drop user; from being passed through. Anyway, it's four years after the fact, but hopefully my answer is of some use.

like image 38
andyengle Avatar answered Nov 02 '22 06:11

andyengle