angularangular-reactive-formsangular-custom-validators

Reactive forms angular show error for pattern in angular


I have reactive form like this

this.form = this.formBuilder.group({
      email: ['', [
        Validators.required,
        Validators.maxLength(120),
        Validators.pattern('^[^\\s@]+@[^\\s@]+\\.[^\\s@]{1,}$')
      ]],
    });

Now I need to display error for different error, like this

<div class="invalid-feedback" *ngIf="form.controls.email.errors.pattern">THIS EMAIL NOT VALID</div>

But I got error Cannot read property 'pattern' of null Does anybody had similar problem with showing error for pattern?


Solution

  • You either fail or pass the validation. when you pass the validation form.controls.email.errors does not exist.

    To overcome that: you need to replace errors with errors? as below:

    <div class="invalid-feedback" *ngIf="form.controls.email.errors?.pattern">THIS EMAIL NOT VALID</div>