Full answer
An AsyncValidatorFn receives the control and returns Observable<ValidationErrors | null> (or a Promise). Angular runs async validators only when all sync validators pass, and while one is running the control status is PENDING.
Problem: Angular calls the validator on every value change, and each call would send a request. Also, an old slow response could arrive after a newer one.
Solution inside the validator:
- Return
timer(400).pipe(...). Angular unsubscribes from the previous validator Observable when a new value arrives, so the previous timer is cancelled: that is the debounce. switchMap(() => api.isTaken(value))makes the request. Unsubscribing cancels it, so an old response is never used.map(taken => taken ? { usernameTaken: true } : null).catchError(() => of(null)): if the server fails, do not block the user forever. Decide whether a failed check means valid (as here) or an error like{ checkFailed: true }.
Other points:
updateOn: 'blur'on the control (or{ updateOn: 'blur' }inFormControl) validates when the user leaves the field. It is a simple alternative.- Show feedback:
control.pendingfor "Checking...",control.hasError('usernameTaken')for the error. - The submit button should consider
form.pending. A form that isPENDINGis neither valid nor invalid, soform.invalidis false while pending. Disable submit whenform.invalid || form.pending. - The server must still check at submit time. A client check is advice, because someone else can take the name a second later.
- Provide the validator from a service so it can be tested with a fake API:
inject(UsernameService)inside a factory function.
Test with fakeAsync: set a value, tick(400), flush the HTTP mock, then check the errors.
typescript
import { Component, Injectable, inject } from '@angular/core';
import { AbstractControl, AsyncValidatorFn, FormControl, ReactiveFormsModule, ValidationErrors, Validators } from '@angular/forms';
import { Observable, catchError, map, of, switchMap, timer } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class UsernameService {
isTaken(name: string): Observable<boolean> {
return of(['asha', 'ravi'].includes(name.toLowerCase()));
}
}
export function usernameFree(service: UsernameService): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> =>
timer(400).pipe(
switchMap(() => service.isTaken(control.value as string)),
map((taken) => (taken ? { usernameTaken: true } : null)),
catchError(() => of(null)),
);
}
@Component({
selector: 'app-username',
imports: [ReactiveFormsModule],
template: `
<label for="u">Username</label>
<input id="u" [formControl]="username" />
@if (username.pending) { <small>Checking...</small> }
@if (username.hasError('usernameTaken')) { <small role="alert">That name is taken.</small> }
<button [disabled]="username.invalid || username.pending">Register</button>
`,
})
export class UsernameComponent {
private readonly service = inject(UsernameService);
readonly username = new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
asyncValidators: [usernameFree(this.service)],
});
}Angular 20.3, strict template check passes. A Karma test with fakeAsync checks the pending state, the error for a taken name, and the valid result for a free name.
Key points
- An async validator returns an Observable of errors or null, and sets the control to `PENDING`.
- Debounce with `timer` and cancel with `switchMap`, because Angular unsubscribes from the old validator.
- Handle errors, show a pending state, and consider `form.pending` on submit.
- The server must check again on submit.
Common mistakes
- Sending a request on every keystroke.
- Letting a failed request leave the control pending forever.
- Enabling submit while the form is pending.
Follow-ups
- Why does Angular skip async validators when a sync validator fails?
- How would you test the debounce?
- What does `updateOn: 'blur'` change?
Tips
- Explain that unsubscribing is the debounce mechanism.
- Mention the `pending` status and the submit button.
- Say that the server check at submit is still required.
Evaluation rubric
- Writes a debounced, cancellable async validator.
- Handles errors and pending state.
- Considers testing and server validation.