Validation for passwords with special characters

点点圈 提交于 2020-07-03 12:00:28

问题


I want to Add a validation for my password with special characters. My problem is when I use '%' it wont work. How can I add a validation for special characters properly?

$.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
});

回答1:


You can get through your requirement using a single regex alone. You may try the regex below:

^(?=\D\d)(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=[^-!@._*#%]*[-!@._*#%])[-A-Za-z0-9=!@._*#%]*$

Explanation of the above regex:

^, $ - 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.

You can find the demo of the above regex in here.

Sample implementation of the above regex in 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);

References:

  1. Recommended Reading: Principle of Contrast.


来源:https://stackoverflow.com/questions/62400363/validation-for-passwords-with-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!