简体   繁体   中英

Regular Expression in Javascript for password validation

I am trying to create a regular expression that validates a user's password when they create it. The password needs to be:

  1. at least 6 characters long and can be any type of character
  2. each character that is used needs to appear in the password exactly 3 times.

Good examples:

AAABBB
ABABBA
+++===
+ar++arra
myyymm
/Arrr/AA/

Does anyone know which regex would accomplish this?

You can ease yourself by sorting the password before testing it:

 $('button').on('click', function(){ var s = $('#password').val(); var split = s.split("").sort().join(""); if(/^(?:(.)\\1{2}(?!\\1)){2,}$/.test(split)) console.log("Valid password"); else console.log("Invalid password"); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <input id="password"> <button>Test me</button> 

For 1st option you have to check without regex.

var str = "your password";
var pattern = /(.)(.*\1){3}/;
if(str.length >= 6){
   // It will give you boolean as return
   // If it is match then it return true else false
   pattern.test(str);
}

An alternative solution since you're allowing code (which your question imply you wouldn't ;)

Using a function like verifyPass below should do the trick. It gradually replaces any valid three letter combination with an empty string. Checking that this is done in more than one iteration (it's at least 6 characters) and ending up with an empty string in the end, means it's a valid password.

 function verifyPass(pass) { var re = /^(.)((?:(?!\\1).)*)\\1((?:(?!\\1).)*)\\1((?:(?!\\1).)*)$/, cnt=0; while(re.test(pass)) { pass = pass.replace(re, '$2$3$4'); cnt++; } return pass==='' && cnt>1; } var testItems = [ '123123123', 'AAABBB', 'AAABBBAAA', 'Qwerty', 'ABABBA', '+++===', '111', 'qweqwd', 'sdcjhsdfkj', '+ar++arra', 'mYYYmms', '/Arrr/AA/' ]; testItems.forEach(function(item) { document.write('<span style="color:' + (verifyPass(item) ? 'green' : 'red') + ';">' + item + '</span> <br/>'); }); 

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