Regex to validate passwords with characters restrictions

后端 未结 3 903
渐次进展
渐次进展 2021-01-13 18:53

I need to validate a password with these rules:

  • 6 to 20 characters
  • Must contain at least one digit;
  • Must contain at least one letter (case in
3条回答
  •  醉梦人生
    2021-01-13 19:41

    I'm not completely sure I have this right, but since your last requirement is "Can contain the following characters: !@#$%&*" I am assuming that other special characters are not allowed. In other words, the only allowed characters are letters, digits, and the special characters !@#$%&*.

    If this is the correct interpretation, the following regex should work:

    ^((?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9!@#$%&*]{6,20})$
    

    Note that I changed your character class [A-z] to [a-zA-Z], because [A-z] will also include the following characters: [\]^_`

    I also added beginning and end of string anchors to make sure you don't get a partial match.

提交回复
热议问题