Sub topic 8
Asynchronous validators
This chapter assumes you can write a synchronous validator, attach it to a FormControl, and read errors in a template. It also assumes you know pipe, map, and switchMap from RxJS. The goal is a validator that asks a server whether a value is acceptable, without flooding the server and without leaving the form in a confusing state.
When a validator must be asynchronous
A synchronous validator can only judge a value from data already in the browser. Some rules need an answer from somewhere else:
- Is this username already registered?
- Does this promo code exist?
- Is this address inside a delivery zone?
Angular handles these with async validators. An async validator has the same job as a sync one: it returns ValidationErrors or null. The difference is that it delivers the result later, through an Observable (or a Promise).
The AsyncValidatorFn contract
The type is AsyncValidatorFn. It is a function that takes an AbstractControl and returns Observable<ValidationErrors | null> or Promise<ValidationErrors | null>.
Three rules follow from how Angular subscribes to the result:
- The observable must emit a result and then complete. Angular waits for completion before it applies the result. An
HttpClientcall completes by itself. A long-lived stream such as a formvalueChangesor a WebSocket does not, so addtake(1)orfirst(). - Emit
nullfor valid and an error object for invalid, exactly as in a sync validator. - If the observable never emits, the control stays
PENDINGforever.
Attaching an async validator
Async validators have their own slot, separate from sync validators. In the options object it is asyncValidators. In the older positional constructor it is the third argument.
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { UsernameService, uniqueUsernameValidator } from './unique-username.validator';
export function buildSignupForm(service: UsernameService) {
return new FormGroup({
username: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
asyncValidators: [uniqueUsernameValidator(service)],
}),
});
}Angular runs the two kinds in a fixed order:
- All sync validators run first.
- If any sync validator fails, the control becomes
INVALIDand the async validators are not run. A value that is empty or too short never triggers a request. - If the sync validators pass, the status becomes
PENDINGand the async validators start. - When the observables complete, Angular merges their errors, and the status becomes
VALIDorINVALID.
If you attach several async validators, Angular subscribes to all of them and waits for all to complete. The errors are then merged into one object.
Debouncing with timer and switchMap
By default Angular runs validation on every value change. A user typing "alice" produces five changes. Without care, that is five requests. Here is the validator from the plan:
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)),
);
}Each keystroke makes Angular call the validator function again and subscribe to the new observable. Before it subscribes, Angular unsubscribes from the previous one. This is the mechanism that makes debouncing work:
timer(300)emits once after 300 ms.- If the user types again within 300 ms, Angular unsubscribes, the timer is cancelled, and
switchMapnever runs. No request is sent. - If the user pauses for 300 ms, the timer fires and
switchMapcalls the service. - If the user types while a request is already in flight, the unsubscribe also cancels the pending
HttpClientrequest, so an old response cannot overwrite a newer one.
timer(300) emits once and completes, and the inner request completes too. This satisfies the completion rule above.
The next diagram shows the status of a control as validation runs.
A full example: component and service
The service below uses HttpClient. The endpoint is an example, so replace it with your own. Your app config needs provideHttpClient().
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, map } from 'rxjs';
import { UsernameService } from './unique-username.validator';
@Injectable({ providedIn: 'root' })
export class HttpUsernameService implements UsernameService {
private readonly http = inject(HttpClient);
isTaken(username: string): Observable<boolean> {
return this.http
.get<{ taken: boolean }>('/api/usernames/check', { params: { username } })
.pipe(map((response) => response.taken));
}
}Using params lets Angular encode the value, so a username with special characters cannot break the URL. The component below shows all three states in its template:
import { Component, inject } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { HttpUsernameService } from './http-username.service';
import { uniqueUsernameValidator } from './unique-username.validator';
@Component({
selector: 'app-signup',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<label for="username">Username</label>
<input id="username" type="text" formControlName="username" />
@if (form.controls.username.pending) {
<p>Checking availability...</p>
}
@if (form.controls.username.hasError('usernameTaken')) {
<p>That username is already taken.</p>
}
<button type="submit" [disabled]="form.invalid || form.pending">Sign up</button>
</form>
`,
})
export class SignupComponent {
private readonly usernames = inject(HttpUsernameService);
readonly form = new FormGroup({
username: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
asyncValidators: [uniqueUsernameValidator(this.usernames)],
}),
});
submit(): void {
if (this.form.valid) {
console.log('Submitting', this.form.getRawValue());
}
}
}form.invalid is false while the form is PENDING, so a button that checks only invalid stays enabled during a check. The || form.pending part closes that gap. The valid getter is true only for the VALID status, so the if (this.form.valid) guard in submit() is safe.
Edge cases and decisions
Empty and non-string values
The validator above calls the service even when the value is '' or null. Add a guard at the top so you do not waste a request:
const value = control.value;
if (typeof value !== 'string' || value.length === 0) {
return of(null);
}When the control has Validators.required, the sync step already stops empty values, so the guard matters mainly for optional fields.
Failed requests
The example uses catchError(() => of(null)). This is a fail-open choice: if the check itself fails, the field is treated as valid. The user can continue, and the server must still reject a duplicate when the form is submitted. The alternative is fail-closed: return of({ usernameCheckFailed: true }) and show "Could not verify, try again." That is safer for rules the server cannot re-check later, but a network outage then blocks the whole form. Pick based on what the final submit enforces.
Editing existing data
On an edit form, the user's current username is "taken" by themselves. A factory can accept the original value and return null when control.value equals it. Without this check the form is invalid before the user changes anything.
Reduce checks with updateOn
By default every change triggers validation. Setting updateOn: 'blur' on the control validates only when the user leaves the field.
new FormControl('', {
nonNullable: true,
asyncValidators: [uniqueUsernameValidator(service)],
updateOn: 'blur',
});With updateOn: 'blur', the value and validity update on blur. You still get a single request per visit to the field, and the timer is no longer needed for debouncing. The cost is that feedback comes later. For expensive checks, blur is often the better trade-off. For cheap checks, a debounce gives faster feedback.
Revalidating without a value change
If the answer can change without the user touching the field, for example after another field changes, call control.updateValueAndValidity(). This reruns sync validators, and the async ones if the sync step passes. Pass { emitEvent: false } to avoid triggering valueChanges subscribers again.
Async validators on groups
A FormGroup accepts asyncValidators in the same way. The validator receives the group, so you can check a combination of fields, such as an email plus a company domain. The result goes onto the group's errors, not onto a child control. Cross-field validation is covered in the previous chapter, and the same read-from-group.get(...) pattern applies.
Testing an async validator
An async validator with a timer needs controlled time. Use fakeAsync and tick from @angular/core/testing. Attach the validator to a real FormControl so you test the status as well as the errors:
import { fakeAsync, tick } from '@angular/core/testing';
import { FormControl } from '@angular/forms';
import { of } from 'rxjs';
import { uniqueUsernameValidator } from './unique-username.validator';
describe('uniqueUsernameValidator', () => {
const service = { isTaken: (name: string) => of(name === 'alice') };
function createControl(value: string): FormControl<string> {
return new FormControl(value, {
nonNullable: true,
asyncValidators: [uniqueUsernameValidator(service)],
});
}
it('is pending until the debounce elapses, then reports a taken name', fakeAsync(() => {
const control = createControl('alice');
expect(control.status).toBe('PENDING');
tick(300);
expect(control.status).toBe('INVALID');
expect(control.errors).toEqual({ usernameTaken: true });
}));
it('is valid for a free name', fakeAsync(() => {
const control = createControl('bob');
tick(300);
expect(control.valid).toBeTrue();
}));
});toBeTrue() is a Jasmine matcher. In Jest, use toBe(true). The service here is a plain object, so no TestBed is needed. To test cancellation, call control.setValue('alic'), then tick(100), then control.setValue('alice'), and check that the service was called once. A Jasmine spyOn or a Jest jest.fn on isTaken does this.
Common errors
| Symptom | Likely cause |
|---|---|
| Control is `PENDING` forever | The observable never emits or never completes. Add `take(1)` or `first()`, or check that the service returns a value. |
| A request fires on every keystroke | No debounce, such as `timer`, in front of `switchMap`, and `updateOn` is `'change'`. |
| Async validator never runs | A sync validator is failing. Async validators wait until sync validators pass. |
| Submit button enabled during a check | The button tests `invalid` only. Also test `pending`. |
| Stale result shown for old input | `mergeMap` or `concatMap` used instead of `switchMap`, so old responses are not cancelled. |
| Validator runs in the constructor and the form starts `PENDING` | Expected. Initial validation runs when the control is created. |
Exercise
A signup form shows a "Checking availability..." message and a disabled Submit button even after the user stopped typing, and it never goes away. The async validator is (control) => this.http.get('/api/check').pipe(map(() => null)) using HttpClient. A teammate then changes it to (control) => control.valueChanges.pipe(map(() => null)) and the symptom stays the same. What is wrong with the second version, and how do you fix it?
Show answer
control.valueChanges is a long-lived stream. It does not emit until the value changes again, and it never completes, so Angular never receives a result and the control stays PENDING. Fix it by using a source that completes after a result, such as an HttpClient call or of(null). If you must start from a non-completing stream, add take(1) or first(). For the first version, check that the request is reaching the server and that the /api/check response is not a hanging request.
Exercise
Explain why timer(300).pipe(switchMap(() => service.isTaken(value))) debounces input, even though the validator contains no explicit debounce operator.
Show answer
Angular calls the validator function on each value change and unsubscribes from the observable returned for the previous value. If the user types again within 300 ms, the earlier timer is cancelled before it emits, so switchMap never calls the service. Only a value that stays unchanged for 300 ms reaches isTaken. An in-flight request is also cancelled by the same unsubscribe.