Sub topic 3
Asynchronous Validators
Assume you know TypeScript, Angular templates, reactive forms, and basic RxJS. An asynchronous validator checks a value through a delayed operation, such as an HTTP request. It returns an Observable that emits a ValidationErrors object or null, then completes.
Asynchronous validators
This validator checks whether a username is already taken:
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)),
);
}timer(300) waits for 300 milliseconds. switchMap cancels the previous pending check when a newer value arrives. This prevents a slow response for an old value from overwriting the current result.
Attach asynchronous validators separately from synchronous validators:
const form = new FormGroup({
username: new FormControl('', {
nonNullable: true,
validators: [Validators.required],
asyncValidators: [uniqueUsernameValidator(usernameService)],
}),
});Pending state, updateOn, and revalidation
While the observable has not emitted, the control status is PENDING. Use that state to show progress:
@if (form.controls.username.pending) {
<p>Checking username...</p>
}
@if (form.controls.username.hasError('usernameTaken')) {
<p>That username is unavailable.</p>
}Set updateOn: 'blur' when validation should wait until the user leaves the field:
new FormControl('', {
asyncValidators: [uniqueUsernameValidator(usernameService)],
updateOn: 'blur',
});Angular reruns validation when the control value changes or when you call updateValueAndValidity(). Call the method after changing validator configuration.
Validator directives for template-driven forms
A directive can register the same validation logic with NG_VALIDATORS:
@Directive({
selector: '[appForbiddenName]',
standalone: true,
providers: [
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => ForbiddenNameDirective),
multi: true,
},
],
})
export class ForbiddenNameDirective implements Validator {
@Input('appForbiddenName') forbiddenNames: string[] = [];
validate(control: AbstractControl): ValidationErrors | null {
return forbiddenNameValidator(this.forbiddenNames)(control);
}
}multi: true preserves Angular's other validators.
Unit testing validators
Call a synchronous validator with a standalone FormControl. No component or TestBed is required:
it('rejects a forbidden name', () => {
const validator = forbiddenNameValidator(['admin']);
expect(validator(new FormControl('Admin'))).toEqual({
forbiddenName: { value: 'Admin' },
});
});Exercise
Why does an async validator use switchMap after a delay?
Show answer
It cancels the obsolete check when the user enters a newer value, so only the latest validation result is applied.