Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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-z\d!@#$%^&*()_+]{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

like image 711
adiga Avatar asked Jan 14 '15 08:01

adiga


People also ask

What are the requirements for regex for password?

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters 1 Regex for Password must contain 8 characters, 2 letter both lower or uppercase letters and one special character ' * ' 5 digit number 1

How many characters should my password contain?

The password must contain at least: 1 1 uppercase letter 2 1 lowercase letter 3 1 number 4 1 special character 5 8-20 characters 6 Must not start or end with a special character More ...

How do I restrict characters in a regexp?

Your regexp doesn't prohibit any character, it just requires one instance of every class. To restrict the allowed characters, change your . (which means any character) to the set of allowed characters: ^ (?=.*? [A-Z]) (?=.*? [a-z]) (?=.*? [0-9]) (?=.*? [#@$?]) [a-zA-Z0-9#@$?] {8,}$

How to use regex to check valid password in Java?

Match the given string with the Regex. In java, this can be done using Pattern.matcher (). Return true if the string matches with the given regex, else return false. import java.util.regex.*; // Function to validate the password. // Regex to check valid password. // and regular expression. // Driver Code.


1 Answers

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#"));
like image 93
nu11p01n73R Avatar answered Oct 08 '22 01:10

nu11p01n73R