How to validate a user name with regex?

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

    I suggest writing some unit tests to put the Regex through it's paces. This will also help a few months from now when you find a problem with the Regex and need to update it.

    0 讨论(0)
  • 2020-11-27 13:24

    By the looks of it, that rule wouldn't match something like "a_bc", "ab_c", "a_b" or "a_b_c".

    Try: /^[a-zA-Z0-9]+([_\s\-]?[a-zA-Z0-9])*$/ which matches the above cases but not any combination of spaces, dashes or underscores next to each other. Eg: "_-" or " _" are not allowed.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 13:27
    1. Alphanumerical isn't just [a-zA-Z0-9], it's accented, Cyrillic, Greek and other letters, which can be used in username.

    2. (_|-| ) can be replaced by [-_ ] character class

    0 讨论(0)
  • 2020-11-27 13:30

    In my opinion, adding a limited scope to this model would be better

    [a-zA-Z0-9]+([_ -]?[a-zA-Z0-9]){5,40}$

    0 讨论(0)
  • 2020-11-27 13:35

    Another recommendation for Expresso 3.0 here - very easy to use and build up strings with.

    0 讨论(0)
提交回复
热议问题