简体   繁体   English

Javascript中的正则表达式,用于密码验证

[英]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 至少6个字符长,可以是任何类型的字符
  2. each character that is used needs to appear in the password exactly 3 times. 每个使用的字符都需要在密码中正确显示3次。

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. 使用下面的verifyPass类的功能可以verifyPass 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. 检查这是在一个以上的迭代中完成的(至少6个字符),最后以一个空字符串结尾,表示它是有效的密码。

 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/>'); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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