Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Gaurav Singhal

Building Custom Validators in Angular

Gaurav Singhal

  • Jan 13, 2020
  • 14 Min read
  • Jan 13, 2020
  • 14 Min read
Languages Frameworks and Tools


Most applications for web, desktop, and mobile contain various forms with fields to collect user input. But before submitting values to the server, we must validate them.

Validating form values before the submit operation is a crucial task because most of the application contains the form, so there is a chance a user may enter incorrect values or a hacker may try to steal our valuable data.

The Form of Validators

Angular supports two types of primary forms:

  • Template-driven forms
  • Reactive forms

Angular forms are the standard forms, but there may be additional fieldssuch as input box, checkbox, select, and so on.

Every field in a form can act as a FormControl that returns complete information about that single field, including whether the form is valid or not, the actual field value, and other information as well.

By combining all of the form controls, we can have a FormGroup, and it’s required that every single form in Angular have one FormGroup.

These are the two form approaches by which we can create forms, form controls, and form groups, Apart from that, we should have form validation so that we can validate our form before sending values to the server.

Custom Validators in Angular

To validate the different form fields, we should have some business logic so that we will be able to send the valid values to the server.

Angular supports two types of form validators: in-built validators and custom validators. Let’s go through the list of in-built form validators in Angular.

  • Min
  • Max
  • Minlength
  • Maxlength
  • Required
  • Compose
  • Pattern

Other validators are also supported apart from these inbuilt ones, and we can also create a custom form validator if we have a specific requirement to validate any field in the form.

Creating a Custom Form Validator

As we know, sometimes in-built validators may not fulfill our validation requirement, so we may need to write custom validation logic to create custom form validators.

Custom validators take the value from the FormControl, where every input acts as a FormControl. So let’s create a form along with a validator function.

Create a new file called customvalidator.validator.ts and paste the following function.

1import { FormGroup, AbstractControl } from "@angular/forms";
3// To validate password and confirm password
4export function ComparePassword(
5  controlName: string,
6  matchingControlName: string
7) {
8  return (formGroup: FormGroup) => {
9    const control = formGroup.controls[controlName];
10    const matchingControl = formGroup.controls[matchingControlName];
12    if (matchingControl.errors && !matchingControl.errors.mustMatch) {
13      return;
14    }
16    if (control.value !== matchingControl.value) {
17      matchingControl.setErrors({ mustMatch: true });
18    } else {
19      matchingControl.setErrors(null);
20    }
21  };

This is our simple custom validator function, which accepts the name of control along with matchingControlName, which basically compares two different fields for our example.

The next step is to use that custom validator function into our component to initialize the form along with the custom form validator name.

Create a new component called myform, open myform.component.ts, and paste the following source code.

1import { Component, OnInit } from "@angular/core";
2import {
3  FormBuilder,
4  FormGroup,
5  Validators,
6  AbstractControl
7} from "@angular/forms";
8import {
9  ComparePassword,
10} from "../customvalidator/customvalidator.validator";
13  selector: "app-myform",
14  templateUrl: "./myform.component.html",
15  styleUrls: ["./myform.component.css"]
17export class MyformComponent implements OnInit {
18  registerForm: FormGroup;
19  submitted = false;
21  constructor(private formBuilder: FormBuilder) {}
23  ngOnInit() {
24    this.registerForm =
25      {
26        firstName: ["", [Validators.required]],
27        lastName: ["", [Validators.required]],
28        email: ["", [Validators.required,]],
29        password: ["", [Validators.required, Validators.minLength(6)]],
30        confirmPassword: ["", Validators.required]
31      },
32      {
33        // Used custom form validator name
34        validator: ComparePassword("password", "confirmPassword")
35      }
36    );
37  }
39  // Getter function in order to get form controls value
40  get f() {
41    return this.registerForm.controls;
42  }
44  onSubmit() {
45    this.submitted = true;
47    // Returns false if form is invalid
48    if (this.registerForm.invalid) {
49      return;
50    }
52    console.log("Form Values" + JSON.stringify(this.registerForm.value));
53  }

Let me explain what we have done in this component.

  • We have initialized the form using FormBuilder and combined all the form controls using FormBuilder.
  • Along with each and every form control, we have used in-built validators including required, email, and minlength.
  • Apart from those in-built validators, we have used an additional validator, ComparePassword, which accepts the password, confirms it, and returns the result based on the function execution.

This is how we have developed our custom form validator. Let’s implement two more custom form validators for the first name and last name fields.

1// To validate first name
2export function ValidateFirstName(control: AbstractControl) {
3  if (!control.value.startsWith("@")) {
4    return { validFname: true };
5  }
6  return null;

In this function, we will get complete form control using AbstractControl, which is the base class for FormControl, FormGroup, and FormArray.

Using that function, we are validating that the string we are using as the first name should start with the @ operator; otherwise, we return null as a result.

1// To validate last name
2export function ValidateLastName(control: AbstractControl) {
3  if (control.value.length <= 3) {
4    return { validLname: true };
5  }
6  return null;

This is yet another custom form validator that accepts the last name string and validates that the last name should be more than three characters long.

So far, we have created three different custom form validators:

  • ComparePassword
  • ValidateFirstName
  • ValidateLastName

Before moving to the template section, we need to modify our form group source code into the component like this.

1ngOnInit() {
2    this.registerForm =
3      {
4        firstName: ["", [Validators.required, ValidateFirstName]],
5        lastName: ["", [Validators.required, ValidateLastName]],
6        email: ["", [Validators.required,]],
7        password: ["", [Validators.required, Validators.minLength(6)]],
8        confirmPassword: ["", Validators.required]
9      },
10      {
11        // Used custom form validator name
12        validator: ComparePassword("password", "confirmPassword")
13      }
14    );

Now we are done with our custom form validator functions. Our next step is to create visual form into our app template.

Open myform.component.html and paste following lines of code.

1<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
2	<table>
3		<tr>
4			<td></td>
5		</tr>
6		<tr>
7			<td>First Name :</td>
8			<td>
9				<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
10				<div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
11					<div *ngIf="f.firstName.errors.required">First Name is required</div>
12				</div>
13				<div *ngIf="registerForm.get('firstName').errors &&
14      registerForm.get('firstName').dirty &&
15      registerForm.get('firstName').errors.validFname">
16					First name should start with @
17				</div>
18			</td>
19		</tr>
20		<tr>
21			<td>Last Name :</td>
22			<td>
23				<input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.lastName.errors }" />
24				<div *ngIf="submitted && f.lastName.errors" class="invalid-feedback">
25					<div *ngIf="f.lastName.errors.required">Last Name is required</div>
26				</div>
27				<div *ngIf="registerForm.get('lastName').errors &&
28      registerForm.get('lastName').dirty &&
29      registerForm.get('lastName').errors.validLname">
30					Last name should be > 3
31				</div>
32			</td>
33		</tr>
34		<tr>
35			<td>Email :</td>
36			<td>
37				<input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && }" />
38				<div *ngIf="submitted &&" class="invalid-feedback">
39					<div *ngIf="">Email is required</div>
40					<div *ngIf="">Email must be a valid email address</div>
41				</div>
42			</td>
43		</tr>
44		<tr>
45			<td>Password :</td>
46			<td>
47				<input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
48				<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
49					<div *ngIf="f.password.errors.required">Password is required</div>
50					<div *ngIf="f.password.errors.minlength">Password must be > 6 character long</div>
51				</div>
52			</td>
53		</tr>
54		<tr>
55			<td>Confirm Password :</td>
56			<td>
57				<input type="password" formControlName="confirmPassword" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }" />
58				<div *ngIf="submitted && f.confirmPassword.errors" class="invalid-feedback">
59					<div *ngIf="f.confirmPassword.errors.required">Confirm Password is required</div>
60					<div *ngIf="f.confirmPassword.errors.mustMatch">Password should be same as Confirm password</div>
61				</div>
62			</td>
63		</tr>
64		<tr>
65			<td>
66				<button class="btn btn-primary">Register</button>
67			</td>
68		</tr>
69	</table>

This looks huge at first glance, but don't worry—we'll look at each of the controlsbriefly.

The most important part is the form tag, which denotes that this is a form along with the additional properties, like formGroup, that we have initialized in the component.

Along with the form, we have one action attached to it called ngSubmit. This means that as soon as the form gets validate and submitted, the function onSubmit will be triggered into the component.

In the form, we have different input controls, along with the additional div section in order to show some error into the form, which looks like this.

1<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
3<div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
4	<div *ngIf="f.firstName.errors.required">First Name is required</div>

The div section is used to show the error for the required field validation, which directly comes from the error object of the form group.

But if we have a custom form validator, it's possible that the error object may be different. For that, we can get the errors by using the form name, which can be implemented like this into the template.

1<div *ngIf="registerForm.get('firstName').errors &&
2      registerForm.get('firstName').dirty &&
3      registerForm.get('firstName').errors.validFname"
5		The first name should start with @

Here we are getting the errors for the specific form of control by using its name and other parameters, like touched, dirty, and validFname, which is our custom error generated directly from the custom validator function.

For the password comparison, we have created an error object called mustMatch into the custom validator function, hence it can be used like this.

1<input type="password" formControlName="confirmPassword" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }" />
3<div *ngIf="submitted && f.confirmPassword.errors" class="invalid-feedback">
4	<div *ngIf="f.confirmPassword.errors.required">Confirm Password is required</div>
5	<div *ngIf="f.confirmPassword.errors.mustMatch">
6    	Password should be same as Confirm password
7    </div>

This is how we have accessed the different errors based on the error object, whether it’s froman in-built validator or from the custom validator function.

Let’s run this complete, full-fledged example and see how it works.

Custom validator initial output

As you can see, we have provided wrong values against the validation criteria, and this is how the error appeared with the form control.

Now let’s provide the wrong password, confirm the password, and see whether the password comparison validator function works or not.

Final app output

Provide incorrect value to each of the form fields, and we can see the error appears showing that our password and confirm password do not match.

We have now implemented complete end-to-end custom form validators using different strategies and structures. Thus we can use different approaches based on the custom validation criteria.


In this guide, we have gone through the different types of validators and understood why we need custom form validator in our Angular application.

Custom form validators are pretty handy when it comes to custom validation logic for the underlying business logic, and I hope this guide will help you to implement custom form validations. Stay tuned for more advanced guides.