Regex for Password: “Atleast 1 letter, 1 number, 1 special character and SHOULD NOT start with a special character”

后端 未结 1 1406
一向
一向 2020-12-16 17:51

I need a regular expression for a password field.

The requirement is:

  1. The password Must be 8 to 20 characters in length

  2. Must contain

相关标签:
1条回答
  • 2020-12-16 18:26

    Its simple, just add one more character class at the begining

    ^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d][A-Za-z\d!@#$%^&*()_+]{7,19}$
    
    • [A-Za-z\d] Ensures that the first character is an alphabet or digit.

    • [A-Za-z\d!@#$%^&*()_+]{7,19} will match minimum 7 maximum 19 character. This is required as he presceding character class would consume a single character making the total number of characters in the string as minimum 8 and maximum 20.

    • $ Anchors the regex at the end of the string. Ensures that there is nothing following our valid password

    Regex Demo

    var pattern = new RegExp(/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d][A-Za-z\d!@#$%^&*()_+]{7,19}$/);
    
    console.log(pattern.test("!@#123asdf!@#"));
    
    console.log(pattern.test("123asdf!@#"));
    
    console.log(pattern.test("12as#"));

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