Reactive Forms and Validations — Part 4

Parekh Dharmesh T
3 min readDec 7, 2021

Cross Field Validation

This is again continuation of my previous blog named Reactive Forms and Validation. Today we will discuss about cross field validation scenarios that is very common in real world application.

Sometimes simple FormControl (field) validation is not suffice. We need to compare across two or more FormControls (fields). Below are examples of cross field validations.

Example 1 — Password and Confirm password must match
A common example of this is to compare confirm password with password field. if both does not match, we have to inform user about it (display error message).

Example 2 — Compare start and end date
This is also very common example. our end date must be greater than start date.

Example 3 — Compare email and confirm Email address

Let us implement example 3 in our customer sign up form. how this can be achieved in reactive forms.

Trick To implement cross field validation, we need to define a nested FormGroup for FormControls (start and end) to be validated together. They both should be defined as a group in HTML and Component.

Lab — Implement cross field validation for mail and confirm email address

  1. Add confirm email html in template
  2. Add confirm email FormControl in component file.
  3. Add FormGroup for above two FormControls
  4. Add container tag (div) and move both formControl html inside div tag
  5. Define FormGroupName in div tag and set value to emailGroup
  6. Last but not least, wherever you are referring email or confirmemail for checking valid or touched etc.. then apply emailGroup prefix. (see below html.

Now we are done with changes to be done in template and component file. now let us add custom validator for cross field validation. (confirm email value must match with email value else display error message).

  1. Define emailMatcher function in component file and if it is consumed in other parts of application then add it in separate file so that it can be imported and consume.
  2. Add validator in FormGroupControl as a 2nd parameter.

That’s it. now let us verify cross validation.

Cross field validation result

Custom Validator — Part 3

--

--