I wrote a Regex to match first / last name for a registration form in my web site. The requirements are:
-
or '
are acceptable Is there any way to make my expression shorter?
^[a-zA-Z]{2,12}['-]?[a-zA-Z]{1,10}\s?[a-zA-Z]{2,12}['-]?[a-zA-Z]{1,10}$
Is it too much restrictions for a name field?
First with your regex the response is up to 47 chars : 12+1+10+1+12+1+10.
I think the best way for you is to allow 44 chars from letters, coma, minus or white space.
You can force the first char to be a letter :
^[a-zA-Z][a-zA-Z\-'\s]{0,43}$
Here is what names your code might miss:
Jo Blow not passed
Hyoung Kyoung Wu not passed
Mike O'Neal not passed
d'Are to Beaware not passed
O Henry Smith not passed
Mathais d'Arras not passed
Martin Luther King Jr not passed
George De FunkMaster not passed
Kurtis B-Ball Basketball not passed
Ahmad el Jeffe not passed
An Ni not passed
You can try this one that can handle almost all names
^[^- '](?=(?![A-Z]?[A-Z]))(?=(?![a-z]+[A-Z]))(?=(?!.*[A-Z][A-Z]))(?=(?!.*[- '][- ']))[A-Za-z- ']{2,}$
Jo Blow passed
Hyoung Kyoung Wu passed
Mike O'Neal passed
d'Are to Beaware passed
O Henry Smith passed
Mathais d'Arras passed
Martin Luther King Jr passed
George De FunkMaster passed
Kurtis B-Ball Basketball passed
Ahmad el Jeffe passed
An Ni passed
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.