Angular Async Validator Example

In this guide let us learn how to create a custom async validator in Angular. The creating an async validator is very similar to the Sync validators. The only difference is that the async Validators must return the result of the validation as an observable (or as Promise).

Angular does not provide any built-in async validators as in the case of sync validators. But building one is very simple.

How to Create Async Validator

Creating a Async Validator is simple as creating a function, which must obey the following rules

  1. The function must implement the AsyncValidatorFn Interface, which defines the signature of the validator function.
  2. The function must return either an observable or a promise
  3. Return null for valid, or an ValidationErrors if the input is invalid

AsyncValidatorFn 

The AsyncValidatorFn is an Interface, which defines the signature of the validator function.

The function takes the AbstractControl. This is the base class for FormControlFormGroup, and FormArray. The validator function must return a list of errors i.e ValidationErrors or null if the validation has passed. The only difference it has with the Sync Validator is the return type. It must return either a promise or an observable.

Async Validator Example

We build gte validator in how to create a custom validator in Angular tutorial. In this Async Validator Example, let us convert that validator to Async Validator.

Create a new Angular Application. Add the gte.validator.ts and copy the following code.

First, import the AbstractControl and ValidationErrors from the @angular/forms. Since we need to return an observable, we also need to import Observable from the rxjs library.


Best Angular Books
The Top 8 Best Angular Books, which helps you to get started with Angular  

The validator function must follow the AsyncValidatorFn Interface. It should receive the AbstractControl as its parameter. It can be FormControlFormGroup or FormArray.

The function must validate the control value and return ValidationErrors if any errors are found otherwise null. It must return them as observable.

The ValidationErrors is a key-value pair object of type [key: string]: any and it defines the broken rule. The key is the string and should contain the name of the broken rule. The value can be anything, but usually set to true.

The validation logic is very simple. Check if the value of the control is a number using the isNaN method. Also, check if the value is less than or equal to 10. If both the rules are valid and then return null

If the validation fails then return the ValidationErrors. You can use anything for the key, but it is advisable to use the name of the validator i.e gte as the key. Also, assign true as value. You can as well assign a string value.

You can return more than one key-value pair as shown in the above example. The second key requiredValue returns the value 10. We use this in the template to show the error message.

We use the of operator convert the result into an observable and return it

Using the Async Validator

To use this validator first, import it in the component class.

Add the validator to the Async Validator collection of the FormControl as shown below. The async validator is the third argument to the FormControl.

That’s it. The complete app.component.ts code as show below

The complete app.component.html

app.module.ts

The use case for Async Validators

We use the async validator when we need to send an HTTP call to the server to check if the data is valid.

The following code shows how you can send a HTTP Request to verify the data.

If the data is Valid we will return nothing, else we return the ValidationErrors  i.e. ({ 'InValid': true }).

You can also pass parameter to the validator & Inject Service into the validator.

You can also use the combineLatest to merge data from more than one observable and validate the input.

Reference

  1. AsyncValidator
  2. AsyncValidatorFn

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top