简体   繁体   中英

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?

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:

正则表达式可视化

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM