带空格字符的JavaScript密码验证

时间:2014-01-28 11:26:31

标签: javascript jquery

我需要使用JavaScript在以下条件下进行密码验证。我的条件:

  1. 至少一位0-9
  2. 至少一个小写字符
  3. 至少一个大写字符
  4. 必须至少包含一个特殊字符
  5. 长度至少8个字符,最多20个
  6. 注意:空格键也被视为特殊字符。
  7. 我试过

    (?=^.{6,10}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+}{":;'?/>.<,' '])(?!.*\s).*$
    

    但它不起作用。还有其他想法吗?

2 个答案:

答案 0 :(得分:2)

基本解决方案

处理一组验证规则的最佳方式(在我看来)是为每个规则定义一个正则表达式,然后迭代规则并检查它们是否成功。如果任何规则失败,则整个验证失败。

这样的事情:

var rules = [
    /[0-9]/,//at least one digit from 0-9, could also use \d
    /[a-z]/,//at least one lowercase
    /[A-Z]/,//at least one uppercase
    /[!%&*\s]/,//special characters, add more as needed. note that \s checks for whitespace
    /^.{8,20}$///length between 8-20
];

var input = "Something1!";

//validate
var pass = true;
for(var i = 0; i < rules.length; i++){
   var rule = rules[i];
   if(!rule.test(input)){
      pass = false;
      break;
   }
}

Here is a working example


高级解决方案

您可以进一步扩展此解决方案,以允许将专用错误消息与每个规则相关联。你没有一个正则表达式数组,而是拥有一个对象数组 - 每个对象包含正则表达式规则和错误信息。

例如:

var rules = [{
    exp: /[0-9]/,
    msg: 'must contain at least one digit'
}, {
    exp: /[a-z]/,
    msg: 'must contain at least one lowercase'
}, {
    exp: /[A-Z]/,
    msg: 'must contain at least one uppercase'
}, {
    exp: /[!%&*\s]/,
    msg: 'must contain at least one special move'
}, {
    exp: /^.{8,20}$/,
    msg: 'must be 8-20 characters long'
}];

var input = "Something1!";

var pass = true;
for (var i = 0; i < rules.length; i++) {
    var rule = rules[i];
    if (!rule.exp.test(input)) {
        pass = false;
        alert("Error: " + rule.msg);//alert the error message
        break;
    }
}

And here it is in action

答案 1 :(得分:1)

试试这个

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{8,20})