KRISH JACKMAN
KRISH JACKMAN

Reputation: 25

How to add password validation using regular expression in angular 8 with some conditions?

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,}')]]``

Upvotes: 0

Views: 3491

Answers (3)

Abdelrahman Haridy
Abdelrahman Haridy

Reputation: 21

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

Upvotes: 1

JAY PATEL
JAY PATEL

Reputation: 589

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..

Upvotes: 0

Utku Turna
Utku Turna

Reputation: 9

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 ]*">

Upvotes: 0

Related Questions