我需要使用JavaScript在以下条件下进行密码验证。我的条件:
我试过
(?=^.{6,10}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+}{":;'?/>.<,' '])(?!.*\s).*$
但它不起作用。还有其他想法吗?
答案 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;
}
}
高级解决方案
您可以进一步扩展此解决方案,以允许将专用错误消息与每个规则相关联。你没有一个正则表达式数组,而是拥有一个对象数组 - 每个对象包含正则表达式规则和错误信息。
例如:
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;
}
}
答案 1 :(得分:1)
试试这个
((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{8,20})