How to validate a user name with regex?

后端 未结 10 1745
礼貌的吻别
礼貌的吻别 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:25

    You regular expression can be simplified to:

    /^[a-zA-Z0-9]+([_ -]?[a-zA-Z0-9])*$/
    

    Visualized with Regexper:

    As you can see a user name always has to start with an alphanumeric character. Special characters (_, , -) have to be followed by an alphanumeric character. The last character has to be an alphanumeric character.

提交回复
热议问题