Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - reactive form validation pattern doesn't work

I have an Angular 6 reactive form and trying to validate a password with regex pattern and it doesn't work.

               <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }"
                    />
                    <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
                        <div *ngIf="f.password.errors.required">Required</div>
                        <div *ngIf="f.password.errors.pattern">Not valid</div>
                    </div>
                </div>

The regex I am usng is like this:

 ngOnInit() {
     this.registerForm = this.formBuilder.group({
           password: ['', [Validators.required, Validators.pattern('^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$')]],

      });
  }

Whatever I enter in the password I get the error message in the ui Not valid

Any idea what I am doing wrong?

like image 305
user2818430 Avatar asked Jan 02 '23 02:01

user2818430


1 Answers

You need to drop ('') and put (//) instead into parameter in your pattern method. It should be:

password: ['', [Validators.required, Validators.pattern(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$/)]]
like image 61
Vlada Veljkovic Avatar answered Jan 16 '23 13:01

Vlada Veljkovic