Sub topic 8
Asynchronous validators
This chapter assumes you can write a synchronous validator and attach it to a FormControl. It also assumes you know the basics of RxJS Observables: pipe, map, switchMap and subscription.
When a validator must wait
Some checks can't be answered from the control's value alone. "Is this username already taken?" needs a server. An asynchronous validator handles that case. It has the same job as a synchronous one, but it returns an Observable instead of the result directly.
The contract:
- The function receives an
AbstractControl. - It returns an
Observable<ValidationErrors | null>. - The Observable must emit once and then complete. Angular takes the first emitted value as the result. If the Observable never completes, the control stays pending.
The TypeScript type is AsyncValidatorFn.
A username validator
import { AbstractControl, AsyncValidatorFn, ValidationErrors } from '@angular/forms';
import { Observable, catchError, map, of, switchMap, timer } from 'rxjs';
export interface UsernameService {
isTaken(username: string): Observable<boolean>;
}
export function uniqueUsernameValidator(service: UsernameService): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> =>
timer(300).pipe(
switchMap(() => service.isTaken(control.value)),
map((taken) => (taken ? { usernameTaken: true } : null)),
catchError(() => of(null)),
);
}This is a validator factory, like the ones in the earlier chapter. It takes the service as a parameter and returns the real validator. Each part of the pipeline has a purpose:
timer(300)emits once after 300 ms. Angular unsubscribes from the previous validator Observable whenever the value changes. If the user types again within 300 ms, the timer is cancelled and no request is sent. This is a cheap form of debouncing.switchMapswaps the timer for the service call. The call is cancelled if the subscription ends first.mapconverts the boolean into the error object ornull.catchErrorturns a failed request intonull. A network error then doesn't mark the username as taken. Whether that is the right policy depends on your app. Sometimes you want to block submission when the check can't run.
Attaching it
Async validators go in a separate slot from synchronous ones. With the options object, the key is asyncValidators.
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { delay, of } from 'rxjs';
import { UsernameService, uniqueUsernameValidator } from './unique-username.validator';
const fakeService: UsernameService = {
isTaken: (username) =>
of(['admin', 'root'].includes(username.toLowerCase())).pipe(delay(500)),
};
export const form = new FormGroup({
username: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
asyncValidators: [uniqueUsernameValidator(fakeService)],
}),
});Angular runs the synchronous validators first. It runs the async validators only if all of them pass. So an empty or too-short value never reaches the service, and you don't need to guard against it inside the async validator.
The pending state
While an async validator is running, the control's status is 'PENDING'. When it finishes, the status becomes 'VALID' or 'INVALID'.
PENDING means "not known yet". It is neither valid nor invalid, so a template should treat it separately.
<input id="username" type="text" [formControl]="form.controls.username" />
@if (form.controls.username.pending) {
<p>Checking availability...</p>
}
@if (form.controls.username.hasError('usernameTaken')) {
<p>That username is taken.</p>
}
<button type="submit" [disabled]="form.invalid || form.pending">Register</button>form.invalid is false while the form is pending, so a button that checks only invalid would let users submit before the check finishes. Test form.pending as well, or use form.valid, which is true only when the status is VALID.
Common errors
- The Observable never completes. An Observable such as
valueChangesor a Subject keeps the control pending forever. Addfirst()ortake(1), or build the validator from a source that completes, such as anHttpClientcall. - Returning a plain object. An async validator must return an Observable (or a Promise). Returning
{ usernameTaken: true }directly won't work. Useof(...)if the result is already known. - Putting it in the wrong slot. An async validator in the
validatorsarray is treated as a synchronous one. Its returned Observable is read as an error object, and the control ends up with odd, invalid errors. - Calling the service on every keystroke. Without a
timeror similar delay, each key press sends a request. TheswitchMapcancels the older ones, but the traffic still adds up. - Swallowing errors without thinking.
catchError(() => of(null))makes the form valid when the server is down. The server should enforce uniqueness again on submit.
A later chapter covers updateOn, which can run validation on blur or submit instead of on every change.
Exercise
A control has Validators.required in validators and an async validator in asyncValidators. The user leaves the field empty. What is the control's status, and is the async validator called?
Show answer
The status is INVALID because required fails. The async validator is not called, since Angular runs async validators only after every synchronous validator passes.
Exercise
Your registration form's submit button is [disabled]="form.invalid". A user types a username and clicks the button immediately. Why can the form be submitted, and what is the fix?
Show answer
While the async validator runs, the status is PENDING, so form.invalid is false and the button stays enabled. Disable the button with form.invalid || form.pending, or enable it only when form.valid is true.