Angular 11 material form field show validation error in one line

Viewed 275

I have been struggling with the errors not showing for a regex valuation with at least one no, char, special char and number.

TypeScirpt

<mat-form-field class="form-element">
   <input matInput id="password1" placeholder="New password" formControlName="password1">            
   <label   *ngIf="resetPasswordForm.get('password1').errors && resetPasswordForm.get('password1').hasError('required') && 
        (resetPasswordForm.get('password1').dirty || resetPasswordForm.get('password1').touched)" >Errorasdf</label>
</mat-form-field>  

resetPasswordForm = this.formBuilder.group({
  password1: ['',[ Validators.required, Validators.pattern(/^(?=\D*\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=.*[$@$!%*?&*()]).{8,16}$/) ]],
  password2: ['',[ Validators.required, Validators.pattern(/^(?=\D*\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=.*[$@$!%*?&*()]).{8,16}$/) ]],
  
})
2 Answers

HTML and Typescript The previous solution seemed to only work when entering the values for the first time. If an error happened the Validator event would not clear the error message. Here is a password tested and working code with a-z , A-Z, 0-9, special character and a length of 8 characters, this must be in any order.

    regexp: RegExp = /(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])/;

resetPasswordForm = this.formBuilder.group({
  password1: ['',[ Validators.minLength(8), Validators.pattern(this.regexp)]],
  password2: ['',[ Validators.minLength(8), Validators.pattern(this.regexp)]],
  
})

      <mat-form-field class="form-element">
        <input matInput id="password1" placeholder="New password" formControlName="password1">
        <mat-error style="color: red;" *ngIf="resetPasswordForm.controls['password1']">Minumum 8 length with 1 upper, lower case letters, 1 symbol and 1 number</mat-error>
      </mat-form-field>  

      
      <BR>
      <mat-form-field class="form-element">
        <input matInput id="password2" placeholder="Confirm password" formControlName="password2">
        <mat-error style="color: red;" *ngIf="resetPasswordForm.controls['password2']">Minumum 8 length with 1 upper, lower case letters, 1 symbol and 1 number</mat-error>
      </mat-form-field> 

Found a single liner that works a charm, have seen some scary lengthy solutions, this one works nicely.

      <mat-form-field class="form-element">
        <input matInput id="password1" placeholder="New password" formControlName="password1">
        <mat-error style="color: red;" *ngIf="resetPasswordForm.controls['password1']">Minumum 8 length with 1 upper, lower case letters, 1 symbol and 1 number</mat-error>
      </mat-form-field> 
Related