简体   繁体   中英

Regex to accept first and last name with a space but no special characters

So I'm trying to come up with regex to accept first and last name, but the first and last name is mandatory. Special characters are not allowed except - and , and . and ' I would also like to make the first and last name min length 2 chars each.

Some examples. Invalid - firstname

Invalid - lastname

Invalid - f lastname

Invalid - firstname l

Valid - firstname lastname

Valid - f-name lastname

Valid - fname l'name

I have this regex (.*)([A-Za-z ,.'-]){2} ([A-Za-z ,.'-]){2}(.*) which seems to work for everything except excluding the other special characters like !@ etc. I think the issue is because we must match min length for first and last name, with acceptable characters like in above regex. But by excluding other special characters, it essentially reverses the logic.

Here is my regexr

UPDATE for those interested I used two regex matches to get around this issue. The second regex is for more than one of the allowed special characters.

var match = nameVal.match(/^[A-Za-z][A-Za-z,.'-]+ +[A-Za-z][A-Za-z,.'-]+$/gm);
var match2 = nameVal.match(/([.,\-']{2})/g);

Thanks @tshiono for you help.

Would you please try the following:

^[A-Za-z,.'-]{2,} +[A-Za-z,.'-]{2,}$

Demo

If you want first and last name not to start with special characters, please try instead:

^[A-Za-z][A-Za-z,.'-]+ +[A-Za-z][A-Za-z,.'-]+$

[UPDATE]
As for the forked requirement not to repeat the special character, how about:

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

Demo2

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM