Tuesday, 11 February 2020

Angular material form level validations

@angular/cli: 8.3.23
Source: GitHub

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:

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.





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.



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



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!