Asynchronous Validators
In this lesson, we'll learn how to write an asynchronous validator.
We'll cover the following
We’re going to create another validator. The next validator we’ll create will demonstrate how to write asynchronous validators. Every validator we’ve worked with and written has run synchronously.
In some cases, we may need to make a request to a server to validate a value. Requests are asynchronous. We’ll need to wait until a response is given before we can allow the user to proceed.
Asynchronous validators are created similarly to synchronous validators. Here are the steps we’ll take to create one:
- Generate a new class for the validator
- Implement the
AsyncValidator
interface - Define the
validate
method - The
validate
method should return an observable or promise that emits null or an object
The async validator we’ll be creating will check if the password the user provided is safe. There’s a free API available, called Enzo, that stores a database of vulnerable passwords. We’ll be making a request to it to help us verify the safety of the user’s password.
Here’s a link to the documentation of the API we’ll be using.
Generating a new class
Let’s begin by generating a new class. In the command line, run the following command:
ng generate class validators/compromisedPassword
This will generate a class file and test file for the class. They’ll be stored in the validators
directory.
Implementing the interface
Let’s implement the interface for an async validator. This step is entirely optional. However, I recommend it for hints on how to write a validator. We’re going to use a different interface than last time. If we’re developing an async validator, we’ll need to use the AsyncValidator
interface. Let’s update the compromised-password.ts
file to the following:
Get hands-on with 1400+ tech skills courses.