0

I am using angular 6. I am trying to validate an email by using regular expression pattern but am not able. Problem is when I am trying these code to validate. Below error message is shwoing:

ReactiveFormComponent.html:12 ERROR TypeError: Cannot read property 'pattern' of null

//ts file

   constructor(private fb: FormBuilder) {
   this.personForm = fb.group({
  'emailAddress': ['', Validators.compose ([Validators.required, 
   Validators.pattern(this.emailPattern)])],
});
}

// html file

<mat-form-field fxFlex>
  <input matInput placeholder="Email" formControlName="emailAddress">
  <mat-error *ngIf="personForm.controls['emailAddress'].errors.pattern">
    Invalid Email.
  </mat-error>
</mat-form-field>
2
  • Can you please share the value of emailPattern. Commented May 14, 2018 at 14:29
  • i have solved my problem. thanks@narm Commented May 14, 2018 at 16:12

1 Answer 1

2

This question mark fixes your problem:

*ngIf="personForm.controls['emailAddress'].errors?.pattern"

For valid input content the errors property is null. And there is no the pattern property in null indeed. You can see this if add a value changes listener and log the errors property value for a different input content:

ngOnInit() {
  this.personForm.get('emailAddress').valueChanges.subscribe(_ => {
    console.log(this.personForm.get('emailAddress').errors);
  });
}

Here is a stackblitz example

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.