How to validate a user name with regex?

后端 未结 10 1726
礼貌的吻别
礼貌的吻别 2020-11-27 12:34

This seems to match the rules I have defined, but I only starting learning regex tonight, so I am wondering if it is correct.

Rules:

  • Usernames can cons
10条回答
  •  感情败类
    2020-11-27 13:40

    Using the POSIX character class for alphanumeric characters to make it work for accented and other foreign alphabetic characters:

    /^[[:alnum:]]+([-_ ]?[[:alnum:]])*$/
    

    More efficient (prevents captures):

    /^[[:alnum:]]+(?:[-_ ]?[[:alnum:]]+)*$/
    

    These also prevent sequences of more than one space/hyphen/underscore in combination. It doesn't follow from your specification whether that is desirable, but your own regex seems to indicate this is what you want.

提交回复
热议问题