问题描述:

I was creating a regular expression in angular to validate password which should have

  1. A number
  2. A uppercase letter
  3. A lowercase letter
  4. Only few symbols i.e [email protected]#$%

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 [email protected]#$% 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
        /[[email protected]#$%]/.test(pass) && // predefined symbol is required
        !/[^[email protected]#$%]/.test(pass) // there is nothing unwanted 
    ) {
        return true;
    }
    return false;
}

Here is jsfiddle to show that it works.

相关阅读:
Top