有人能帮我写一个正则表达式来验证以下密码规则吗?
密码需要包含以下五类字符中的至少三类:
- 英文大写字母(A - Z)
- 英文小写字母(a - z)
- 十进制数字(0 - 9)
- 非字母数字字符(例如:!,$,#或%)
- Unicode字符
密码长度最少为6个字符。
有人能帮我写一个正则表达式来验证以下密码规则吗?
密码需要包含以下五类字符中的至少三类:
密码长度最少为6个字符。
if (password.length < 6) {
alert("password needs to be atleast 6 characters long");
}
var count = 0;
//UpperCase
if( /[A-Z]/.test(password) ) {
count += 1;
}
//Lowercase
if( /[a-z]/.test(password) ) {
count += 1;
}
//Numbers
if( /\d/.test(password) ) {
count += 1;
}
//Non alphas( special chars)
if( /\W/.test(password) ) {
count += 1;
}
if (count < 3) {
alert("password does not match atleast 3 criterias");
}
不确定如何使用正则表达式匹配Unicode字符。其余所有条件均在上面提供。
[A-Za-z!$#%\d\u0100]{6}
匹配 aS1%eĀ
。
\u0100
代表 Ā。您可以插入其他需要的 Unicode 代码。您可以在 这里 找到它们。
编辑:对于最少 6 个字符,正确的正则表达式是 [A-Za-z!$#%\d\u0100]{6,}
。
编辑 2:要包括一系列 Unicode 字符(例如 Latin Extended-B),正则表达式应该像这样:^[A-Za-z!$#%\d\u0100-\u017f]{6,}$
。您可以在 这里 找到 Unicode 代码范围。
编辑 3:我开发了一个小函数,用于检查给定的密码是否符合标准。您需要在函数中定义 Unicode 范围。
function isValidPassword(password) {
var unicodeRange = "\\u0100-\\u0105";
var criteria = ["A-Z","a-z","\\d","!$#%",unicodeRange];
// check whether it doesn't include other characters
var re = new RegExp("^[" + criteria.join("") +"]{6,}$");
if(!re.test(password)) return false;
var minSatisfiedCondition = 3;
var satisfiedCount = 0;
for( var i=0; i < criteria.length; i++) {
re = new RegExp("[" + criteria[i] + "]");
if(re.test(password)) ++satisfiedCount;
}
return (satisfiedCount >= minSatisfiedCondition);
}
这里有一个可用的示例链接。