angular5custom-validators

How to add custom validator to reactive forms in Angular5


I have the following passwordvalidator which I don't know how to attach into the html. The way I am invoking it now it's not working loginForm.controls.password.errors.passwordValidator See below in the actual code.

import { FormControl } from "@angular/forms";

    export class PasswordValidator {

        static getPasswordValidator() {
            return function passwordValidator(control: FormControl): { [s: string]: boolean } {

                // Write code here..
                if (!control.value.match(/^((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{6,})/)) {
                    return { invalidPassword: true };
                }

                return null;
            }
        }
    }

Then this is how I am using it in login.ts

  ngOnInit() {
    this.loginForm = this.fb.group({
      username: ['', [Validators.required, Validators.email]],
      password: ['',
        Validators.compose([
          Validators.required,
          PasswordValidator.getPasswordValidator()
        ]
        )]
    });
  }

But can't find out how to add it to the formcontrol in login.html

<mat-form-field class="example-full-width">
    <input id="password" formControlName="password" matInput placeholder="Password">
  </mat-form-field>
  <br>
  <div *ngIf="loginForm.controls.password.invalid && (loginForm.controls.password.dirty || loginForm.controls.password.touched)"
    class="alert alert-danger">
    <div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.required">
      You must fill out your password
    </div>
    <div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.passwordValidator && !loginForm.controls.password.errors.required">
      Invalid email password
    </div>

Solution

  • You should check if the key invalidPassword exist in errors of that controls or not like that

    <mat-form-field class="example-full-width">
        <input id="password" formControlName="password" matInput placeholder="Password">
    </mat-form-field>
    <br>
    <div *ngIf="loginForm.controls.password.invalid && (loginForm.controls.password.dirty || loginForm.controls.password.touched)"
        class="alert alert-danger">
        <div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.required">
        You must fill out your password
        </div>
        <div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.invalidPassword && !loginForm.controls.password.errors.required">
        Invalid email password
        </div>