4

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?

user2818430
  • 5,853
  • 21
  • 82
  • 148
  • You may check my answer here about style the state of the reactive form control https://stackoverflow.com/questions/51583952/angular-forms-bootstrap-is-invalid-is-valid/51584108#51584108 – Muhammed Albarmavi Jul 29 '18 at 22:36
  • I don't know what your regex mean ,sorry but can you check my answer here about pattern validation https://stackoverflow.com/questions/51551831/validate-input-text-field-based-on-complex-role-and-character-position – Muhammed Albarmavi Jul 29 '18 at 22:39

2 Answers2

9

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,}$/)]]
Vlada Veljkovic
  • 141
  • 1
  • 6
0

You have to put a second backslash before the d's and remove the '^' and '$' like following example:

'(?=.*[A-Za-z])(?=.*\\d)(?=.*[$@$!%*#?&])[A-Za-z\\d$@$!%*#?&]{8,}'
N. Richli
  • 102
  • 1
  • 10