Angular: Cross-field validation for Reactive Forms

Angular: Cross-field validation for Reactive Forms

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

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

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Angular 8 Forms | Angular Reactive and Template Forms

We will see mode-driven approach and template-driven approach in this angular forms. Angualr forms are very useful to get the feedback from the clients.

Reactive Forms in Angular 10 - How to Create a Login Form using Reactive Forms

Learn the basics of reactive forms in Angular 10. In this tutorial, you'll look at how to Create a Login Form using Reactive Forms

Decorator Based Reactive Forms in Angular 

Decorator Based Reactive Forms in Angular  - When working with forms in Angular, we are provided with two choices:-

Advanced Level for Angular Reactive Form

A simple note that help developer walk through Angular Reactive Form which help Angular is more powerful in Enterprise Application.

Angular Reactive Forms: Reactive Forms in Angular 9 Example

Angular Reactive Forms or Model-Driven is another way to construct forms in Angular. In Angular Reactive Forms, the form is built in the component class.