Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Pattern Regex Password Match

Looking for some help for validating password with the following rules:

8+ characters

contains at least 1 upper case letter

contains at least 1 lower case letter

contains at least 1 number

Cannot start with a number

contains no special characters

I had gotten as far as:

(?=.*\d.*)(?=.*[a-z].*)(?=.*[A-Z].*)(?=.*[!#\$%&\?].*).{8,}

but can't seem to figure out how to get the first digit to not match a digit, and set the special character class to not match as well. Any help would be greatly appreciated.

like image 444
Brian Avatar asked Dec 27 '22 02:12

Brian


1 Answers

I find that breaking this down into individual tests is:

  • easier to code
  • easier to read
  • easier to maintain
  • and more flexible when requirements change

Try something like this:

var testPassword = function (password) {
    var minLengthMet = password.length >= 8,
        hasUpper = (/[A-Z]+/).test(password),
        hasLower = (/[a-z]+/).test(password),
        hasNumber = (/[0-9]+/).test(password),
        letterBegin = (/^[A-Za-z]/).test(password),
        noSpecials = !(/[^A-Za-z0-9]+/).test(password);
    return minLengthMet && hasUpper && hasLower && hasNumber && letterBegin && noSpecials;
};

See it in action here: http://jsfiddle.net/H9twa/

like image 194
pete Avatar answered Jan 26 '23 01:01

pete