验证带有特殊字符的密码
我想为带有特殊字符的密码添加验证。我的问题是当我使用“%”时它不起作用。我该如何正确添加特殊字符验证?
$.validator.addMethod("pwcheck", function(value) {
return /^[A-Za-z0-9\d=!\-@._*]*$/.test(value) // consists of only these
&& /[a-z]/.test(value) // has a lowercase letter
&& /[A-Z]/.test(value) // has a upper letter
&& /[!,%,&,@,#,$,^,*,?,_,~]/.test(value) // has a symbol
&& /\d/.test(value) // has a digit
});
您只需使用一个正则表达式即可满足您的要求。您可以尝试以下正则表达式:
^(?=\D\d)(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=[^-!@._*#%]*[-!@._*#%])[-A-Za-z0-9=!@._*#%]*$
上述正则表达式的解释:
^, $
- Denotes the start and end of the line respectively.
(?=\D*\d)
- Represents a positive look-around which asserts for at least a digit.
(?=[^A-Z]*[A-Z])
- Represents a positive look-around which asserts for at least an upper case letter.
(?=[^a-z]*[a-z])
- Represents a positive look-around which asserts for at least a lower case letter.
(?=[^-!@._*#%]*[-!@._*#%])
- Represents a positive look-around which asserts for at least a symbol among the listed. You can add more symbols according to your requirement.
[-A-Za-z0-9=!@._*#%]*
- Matches zero or more among the listed characters. You can add more symbols accordingly.
您可以在 此处
上述正则表达式在 javascript 中的实现示例:
const myRegexp = /^(?=[^\d\n]*\d)(?=[^A-Z\n]*[A-Z])(?=[^a-z\n]*[a-z])(?=[^-!@._*#%\n]*[-!@._*#%])[-A-Za-z0-9=!@._*#%]*$/gm; // Using \n for demo example. In real time no requirement of the same.
const myString = `thisisSOSmepassword#
T#!sIsS0om3%Password
thisisSOSmepassword12
thisissommepassword12#
THISISSOMEPASSWORD12#
thisisSOMEVALIDP@SSWord123
`;
// 1. doesn't contain a digit --> fail
// 3. doesn't contain a symbol --> fail
// 4. doesn't contain an Upper case letter --> fail
// 5. doesn't contain a lowercase letter --> fail
let match;
// Taken the below variable to store the result. You can use if-else clause if you just want to check validity i.e. valid or invalid.
let resultString = "";
match = myRegexp.exec(myString);
while (match != null) {
resultString = resultString.concat(match[0] + "\n");
match = myRegexp.exec(myString);
}
console.log(resultString);
参考文献:
- 推荐阅读: 原理对比。