I was creating a regular expression in angular to validate password which should have
position of any character or symbol is not restricted.
I have tried this regex
/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/
But the above regex takes any special character to be valid... I just want !@#$% this to be valid ele invalid
Try a ng-change
listener - something like the following HTML:
<input ng-model="pw" ng-change="checkPwPolicy(pw)">
<div ng-hide="passwordPolicyValid">Your password is too weak!</div>
Combined with this Javascript inside the scope of the controller of this form:
function checkPwPolicy(password) {
var valid = true;
// at least 1 number
valid = valid && password.match(/[0-9]/).length > 0;
// at least 1 uppercase
valid = valid && password.match(/[A-Z]/).length > 0;
// ...
$scope.passwordPolicyValid = valid;
}
Some things you could do to improve this implementation are that you could make the change listener fire less often, hide the error message when the password has not been touched, as well as adding more detailed errors to the password policy message.
I'm not sure that all the things you want to do are possible in single regex. But you can use a simple validation function that uses some regex's:
function validate (pass) {
if (
/[A-Z]/.test(pass) && // uppercase letter is required
/[a-z]/.test(pass) && // lowercase letter is required
/[0-9]/.test(pass) && // number is required
/[!@#$%]/.test(pass) && // predefined symbol is required
!/[^A-Za-z0-9!@#$%]/.test(pass) // there is nothing unwanted
) {
return true;
}
return false;
}
Here is jsfiddle to show that it works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.