Angular material cross field form validation

anirbmuk

Anirban Mukherjee

Posted on February 21, 2022

Angular material cross field form validation

@angular/cli - 12.0.1
@angular/material - 12.0.1

GitHub logo anirbmuk / MaterialFormDemo

Angular material cross field form validation

This article talks about performing field-level validations across a reactive form using Angular material. The solution aims to perform cross-field form validation and then display the error as mat-error for a selected field.

This is how it would be:

Preview

Both the errors shown above are registered on the FormGroup. But the goal is to display them as mat-error on certain fields.

So how do we do this? To begin with, let's set up the form and the corresponding cross-field validations.

Setup

And we are set up in terms of the code required for the validation part. But how do we display the error as mat-error for a specific field? The mat-error only displays error when the specific field is in an error state. But our requirement is to mark it invalid when the form is invalid (and not just the specific field).

To achieve this, we use an interface called ErrorStateMatcher. This interface implements a method isErrorState, where we can write the logic to mark a form-control as invalid.

We create a class which implements this interface, and then create two instances of this class to use for the two validation methods.

Base class

Instances

Now we map these instances to the fields on which we would want to see the mat-errors.

HTML 1

HTML 2

The [errorStateMatcher] properties are mapped to the respective class instances, which allow the respective fields to be invalid and show mat-error once the form becomes invalid.

Cheers!
Anirban Mukherjee

💖 💪 🙅 🚩
anirbmuk
Anirban Mukherjee

Posted on February 21, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related