user2839497 user2839497 - 1 month ago 12
AngularJS Question

How to add password validation using regular expression in angularjs according to certain criterion?

I want to validate password entered by user for following criteria :

Password should be at least 8 characters long and should contain one number,one character and one special character.

For it I used following regular expression :

^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$


I tried this expression in my angularjs code as below :

<md-input-container class="md-block" style="margin-top:0px;">
<label>Password</label> <md-icon
md-svg-src="/images/icons/ic_lock_black_24px.svg" class="name"></md-icon>
<input type="password" ng-model="newUser.userPassword"
name="userPassword" required
ng-pattern="^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$">
<div
ng-messages="registerForm.userPassword.$error">
<div ng-message="pattern">Password should be atleast 8 characters long
and should contain one number,one character and one special
character</div>
<div ng-message="required">Password should be atleast 8 characters
long and should contain one number,one character and one special
character</div>
</div>
</md-input-container>


In my above code the error message displays when the password field is blank and focus is lost. If user enters a password which doesn't satisfy the criteria I mentioned the error message doesn't show up.

How should I fix this issue? Somebody please help me.

Answer

As far as i understood your problem. Check your console It might be broken on lexical errors.

You forgot slash at start and at end of ng-pattern. Please use ng-pattern="/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$/"

I have created a plunk which might help you. https://plnkr.co/edit/qCjp6a?p=preview

Comments