michbeck
michbeck

Reputation: 745

Check a password in Javascript with a regular expression

i've got an expression checking whether there is at least one number, one lowercase and one uppercase letter and at least 6 characters in a password string. please see my example:

var myPwd = 'test-123H';
console.log('password to check: ' + myPwd); 
//at least one number, one lowercase and one uppercase letter and at least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
var validPassword = re.test(myPwd);
console.log(validPassword);

unfortunatly i can't manage it to achieve two more conditions: the password should be checked against a maximum length of 15 characters and there should be at least 2 numbers instead of one. could anyone tell me the trick?

Upvotes: 3

Views: 211

Answers (1)

anubhava
anubhava

Reputation: 785058

You can modify your regex to this:

var re = /^(?=(\D*\d){2})(?=.*?[a-z])(?=.*?[A-Z]).{6,15}$/;
  • (?=(\D*\d){2}) => will make sure there are at least 2 digits
  • .{6,15} makes sure there are min 6 and max 15 character
  • ^ and $ are line start and line end anchors

Visual Description:

Regular expression visualization

Upvotes: 4

Related Questions