How to create asynchronous validators
Table of Contents
- Async Validator Function
- Usage in Reactive Forms
- Creating Custom Asynchronous Validators
- Combining Validators
- Demo
1. Async Validator Function
In Angular, an asynchronous validator is a function that returns a Promise
or an Observable
. This function takes a form control as an argument and performs asynchronous validation.
2. Usage in Reactive Forms
In reactive forms, you can use asynchronous validators like this:
import { FormBuilder, Validators } from '@angular/forms';
const form = this.fb.group({
username: ['', [Validators.required], [this.uniqueUsernameValidator.bind(this)]],
});
3. Creating Custom Asynchronous Validators
Creating a custom asynchronous validator involves defining a function that returns a Promise
or an Observable
. Here's a quick example:
import { AbstractControl, ValidationErrors, AsyncValidatorFn } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { debounceTime, map, catchError } from 'rxjs/operators';
export function uniqueUsernameValidator(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
const email = control.value;
return of(email).pipe(
debounceTime(300),
map(() => this.userService.checkEmailAvailability(email)),
catchError(() => of(null))
);
};
}
4. Combining Validators
You can easily combine synchronous and asynchronous validators:
const form = this.fb.group({
email: [
'',
[Validators.required, Validators.email],
[this.uniqueUsernameValidator.bind(this)]
],
});
5. Demo
You can find a complete demo of asynchronous validators