Cross Field or Multi Field Validation Angular

In this article, we will learn how to implement Cross Field validation or mult field Validation in Angular. We learned how to validate reactive forms & how to create a custom validator. Those articles showed how to validate a Single Form Control. But some times we also come across fields whose value depends on another field. For example, the following scenario’s requires us to compare two fields.

  1. Start date & end date fields. The end date must be greater than the start date.
  2. Password confirmation. The new password must match the confirm password.

Validation Recap

We assign a validator’s to a form filed, using the second argument of the FormControl as shown below. You can also attach an Async Validator as the third argument.

The above syntax using the FormBuilder.

The Validator will run only when we change the value of userName and Validates only the userName field.

Cross Field Validation

When we validate the multiple fields, we need to ensure that our validation logic runs for each of those fields.

Hence we attach the validator to the Formgroup instead of FormControl. The Validator runs whenever we modify any of the fields in the FormGroup.

Example

Let us create a matchPassword custom validator to compare the password & confirm Password fields.

Since we attach it to a FormGroup, it gets the instance of FormGroup as its parameter. We can use the get method to get the values of both password & confirm FormControls. If they do not match then return the ValidationErrors. Return null if it values passes the Validation.

We attach the matchPassword Validator to FormGroup using its second argument as shown below.

The FormGroup also allows us the add more than one validator using the Validators.compose method.


Best Angular Books
The Top 8 Best Angular Books, which helps you to get started with Angular  

Passing Parameter

You can also pass the parameter to the Multiple Field Validator.

In the following example, we pass the name of the

Refer to the Custom Validator with Parameters in Angular. Also refer to the tutorial on how to inject service into a Validator.

Reference

  1. Cross fields Validation

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top