Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

javascript - Regex for Password: "Atleast 1 letter, 1 number, 1 special character and SHOULD NOT start with a special character"

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 at least one letter and one number and a special character from !@#$%^&*()_+.

  3. Should not start with a special character

I have tried

^(?=.*[a-zA-Z])(?=.*d)(?=.*[!@#$%^&*()_+])[A-Za-zd!@#$%^&*()_+]{8,20}

It works but how do you restrict special characters from beginning the password? Also if you have a more efficient regex than the one mentioned above please suggest.

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

  • [A-Za-zd!@#$%^&*()_+]{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-zd][A-Za-zd!@#$%^&*()_+]{7,19}$/);

console.log(pattern.test("!@#123asdf!@#"));

console.log(pattern.test("123asdf!@#"));

console.log(pattern.test("12as#"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...