In my previous article, I covered the creation of a custom form control validator for my Angular Reactive Form.

Even though, form control validators are very powerful, sometimes are not enough. Imagine a case where you need to validate more than one control at a time. For example, when you have a registration form and you have to check, if the _password_ and _password_confirm_ fields are matching.

Create a custom Form Validator

Let’s start by creating a new file. I recommend that you create a new folder where you keep all your validators.

First of all, I will create and export an arrow function that accepts a FormGroup parameter and returns a ValidatorFn.

With this parameter we are now able to validate more than one controls and, of course, compare their values.

const function passwordMatchValidator(form: FormGroup): ValidatorFn {
   const password = form.controls['password'].value;
   const password_confirm = form.controls['password_confirm'].value;

   if (!password || !password_confirm) {
      return null;
   }
   return (password === password_confirm) ? null : {mismatch: true};
}

#reactive-forms #angular

Angular: Cross-field validation for Reactive Forms
2.60 GEEK