Custom Validators

In this lesson, we'll learn how to write a custom validator.

It’s time to get to the heart of this section, which is writing custom validators. In some cases, you’ll want to create a validator when the validators that come bundled with Angular won’t suffice.

The validator we’ll be creating will check if the passwords from both input fields match. This will be a challenge because validators are typically applied to a single input. We’ll look at how we can use a validator on multiple inputs at the same time.

Here is an overview of the steps we’ll go through to accomplish this:

  1. Generate a class for the validator
  2. Implement the Validator interface on the class
  3. Define a validate method in the class
  4. Return either null or an object with the error

We’ll talk more about each step as we get to them. Let’s get started.

Generating a class

Validators can either be classes or functions. Either one works. You’ll see examples of both in an Angular project. We’ll be going with the class approach because we’ll want to implement an interface to help us ensure we’re creating a proper validator.

The Angular CLI can be used to generate a class. In the command line, run the following command:

ng generate class validators/match

The ng generate class <name> command will generate two files: the class file, and test file for the class. We’re generating the files in a folder called validators. It’s not a requirement to have a folder called validators. You can define validators anywhere in your application. We’re creating a particular directory to keep things organized.

If we open the match.ts file, we’ll find the following:

export class Match {

The command we executed generated an empty class file. This class can be used for anything. We’ll be using it to perform validation.

Implementing a validator

We’re going to tackle step two next. Update the class to the following:

Get hands-on with 1200+ tech skills courses.