【问题标题】:Reg ex - validate password conditions - two out of threeReg ex - 验证密码条件 - 三分之二
【发布时间】:2016-03-03 18:36:47
【问题描述】:

我对密码有以下要求:

  1. 最少 8 个字符。
  2. 密码必须包含数字。
  3. 密码必须包含以下两个组中的字符:

    uppercase alphabet
    lowercase alphabet
    special characters [!@#$...]
    

我使用了以下正则表达式

^(?=.+?[0-9])((?=.*?[a-z])(?=.+?[A-Z]))|((?=.*?[a-z])(?=.+?[~!@#$%^&*()-_=+]))|((?=.+?[A-Z])(?=.+?[~!@#$%^&*()-_=+])).{8,}$

游乐场可以找到[here]

感谢帮助

【问题讨论】:

  • 如何为单独的规则使用 3 个单独的正则表达式,然后计算其中有多少匹配?
  • 你在SO看到类似的问题(结合正则表达式[AND])吗?

标签: javascript regex passwords


【解决方案1】:

尝试创建一个可能的字符值数组,使用Array.prototype.filter() 来检查三个所需组中至少两个的输入字符串

var re = ["abcdefghijklmnopqrstuvwxyz"
          , "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
          , "~!@#$%^&*()-_=+"];

var input = document.querySelector("input");

function check(e) {
  var str = this.value;
  var res = str.length >= this.size // check length
            && /[0-9]/.test(str) // check digit
            && re.filter(function(val) {
                 return new RegExp(str.split("").join("|")).test(val)
               }).length >= 2; // check for at least two of three required groups
  // do stuff
  this.className = res ? "valid" : "invalid"
}

input.oninput = input.onfocus = check;

input.focus();
input.invalid {
  outline: 2px solid red;
}
input.invalid + label {
  display: block;
}
input.valid {
  outline: 2px solid green;
}
label,
input.valid + label {
  display: none;
}
<input type="text" size="8" required="true" id="p" />
<label for="p">Required:
  <br>1. minimum length of 8 characters.
  <br>2. password must contain a number.
  <br>3. password must have characters from two of the following groups:
  <br>&nbsp;&nbsp;&nbsp;a) uppercase alphabet
  <br>&nbsp;&nbsp;&nbsp;b) lowercase alphabet
  <br>&nbsp;&nbsp;&nbsp;c) special characters: ~!@#$%^&*()-_=+</label>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多