0

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

Password should be at least 8 characters as min and 20 as max and should contain one number, one capitalized character, and one special character within this only ,./<>?;':"[]{}\|!@#$%^&*(-=_+ (.

For it I used following regular expression :

Password:['', [Validators.pattern('(?=.[a-z])(?=.[A-Z])(?=.[0-9])(?=.[$@$!%#?^&+=,.-])[A-Za-z\d$@$!%#?^&+=,.-].{8,}')]]``

1

3 Answers 3

1

You can add your pattern by following two steps:

  • In HTML file

    <div *ngIf="f.Password.errors.required">
      This field is mandatory</div>
    <div *ngIf="f.Password.errors.minlength">
      Must be at least 8 digits</div>
    <div *ngIf="f.Password.errors.maxlength">
      Must be Max 20 digits</div>
    <div *ngIf="f.Password.errors.pattern">
      Must contain at least 1 Special Character!</div>
    
  • In ts file

    Password: [null, [ Validators.required, Validators.minLength(8), Validators.maxLength(20), Validators.pattern(/[ !@#$%^&*()_+-=[]{};':"\|,.<>/?][a-zA-Z0-9 ]/) ]]

Run Demo - https://stackblitz.com/edit/angular-shhd1i

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

Comments

0

It is called pattern validation. You can check this link https://angular.io/api/forms/PatternValidator to see angular example. When you put "pattern" attribute (takes regEx) to element it will work as a validator.

<input name="firstName" ngModel pattern="[a-zA-Z ]*">

Comments

0

You can use the pattern like:

/^(?=.*[0-9])(?=.*[a-z][A-Z])(?=.*[//,.?;<>:!@#$%^&*(-=_+)|{}\[\]])([a-zA-Z0-9//,.?;<>\':\"!@#$%^&*(-=_+)|{}\[\]]{8,20})$/
  1. ^ The password string will start this way
  2. (?=.*[A-Z]) The string must contain at least 1 uppercase alphabetical character
  3. (?=.*[0-9]) The string must contain at least 1 numeric character
  4. (?=.*[//,.?;<>':"!@#$%^&*(-=_+)|{}\[\]]) The string must contain at least one special character
  5. (?=.{8,20}) The string must be eight characters to Maximum 20 characters

In angular 8 you can use

<input name="password" ngModel pattern="/^(?=.*[0-9])(?=.*[a-z][A-Z])(?=.*[//,.?;<>:!@#$%^&*(-=_+)|{}\[\]])([a-zA-Z0-9//,.?;<>\':\"!@#$%^&*(-=_+)|{}\[\]]{8,20})$/">

I think this can help..

2 Comments

But, its not accepting these special characters <>|[]{}., so its not working properly.
@KRISHJACKMAN I have updated my answer. so you can check it.

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.