Regular expression for first and last name

后端 未结 24 1912
温柔的废话
温柔的废话 2020-11-22 10:03

For website validation purposes, I need first name and last name validation.

For the first name, it should only contain letters, can be several words with spaces, an

相关标签:
24条回答
  • 2020-11-22 10:09

    As maček said:

    Don't forget about names like:

    Mathias d'Arras

    Martin Luther King, Jr.

    Hector Sausage-Hausen

    and to remove cases like:

    ..Mathias

    Martin king, Jr.-

    This will cover more cases:

    ^([a-z]+[,.]?[ ]?|[a-z]+['-]?)+$
    
    0 讨论(0)
  • 2020-11-22 10:09

    The following expression will work on any language supported by UTF-16 and will ensure that there's a minimum of two components to the name (i.e. first + last), but will also allow any number of middle names.

    /^(\S+ )+\S+$/u
    

    At the time of this writing it seems none of the other answers meet all of that criteria. Even ^\p{L}{2,}$, which is the closest, falls short because it will also match "invisible" characters, such as U+FEFF (Zero Width No-Break Space).

    0 讨论(0)
  • 2020-11-22 10:09

    This seems to do the job for me:

    [\S]{2,} [\S]{2,}( [\S]{2,})*
    
    0 讨论(0)
  • 2020-11-22 10:09

    Fullname with only one whitespace:

    ^[a-zA-Z'\-\pL]+(?:(?! {2})[a-zA-Z'\-\pL ])*[a-zA-Z'\-\pL]+$
    
    0 讨论(0)
  • 2020-11-22 10:09

    If you want the whole first name to be between 3 and 30 characters with no restrictions on individual words, try this :

    [a-zA-Z ]{3,30}
    

    Beware that it excludes all foreign letters as é,è,à,ï.

    If you want the limit of 3 to 30 characters to apply to each individual word, Jens regexp will do the job.

    0 讨论(0)
  • 2020-11-22 10:13

    There is one issue with the top voted answer here which recommends this regex:

    /^[a-z ,.'-]+$/i
    

    It takes spaces only as a valid name!

    The best solution in my opinion is to add a negative look forward to the beginning:

    ^(?!\s)([a-z ,.'-]+)$/i
    
    0 讨论(0)
提交回复
热议问题