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?
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: