1

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 !@#$%

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

4
  • 1
    Have you tried anything? Commented Aug 21, 2015 at 15:43
  • /(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/ I have tried this but it take any symbol... i want to avoid this thing Commented Aug 21, 2015 at 15:46
  • Do you mean by using this with ng-pattern? Commented Aug 21, 2015 at 15:55
  • I don't think this has anything to do with Angular. You're not adding the special symbols you want to include. Try adding (?=.*[!@#\$%]) to your regex, after your last group and before the closing /. Commented Aug 21, 2015 at 15:56

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

the function checkPwPolicy should be defined in controller on $scope

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.