Sub topic 14
Asynchronous validation
This chapter assumes you can write a template-driven form with ngModel, read control state through #name="ngModel", and write a custom validator directive (the forbiddenName example from the previous chapters). It also assumes basic RxJS: Observable, pipe, map, and switchMap.
Why validation sometimes has to wait
Most rules can be checked from the value alone. "Is this at least 3 characters?" answers immediately. Other rules need information the browser doesn't have. "Is this username already taken?" needs the server. An asynchronous validator is a validator that returns an Observable or a Promise of its result instead of the result itself.
Angular handles this with a third control status. Alongside VALID and INVALID, a control can be PENDING, which means an async validator has started and has not answered yet.
The contract of an async validator
A synchronous validator takes a control and returns ValidationErrors | null. An async validator takes the same control and returns an Observable<ValidationErrors | null> or a Promise<ValidationErrors | null>. The meaning of the result is unchanged. null means valid, and an object means invalid, with the object's keys naming the errors.
In template-driven forms you write the validator as a directive that implements AsyncValidator and registers itself under NG_ASYNC_VALIDATORS. Sync validators use NG_VALIDATORS. Using the wrong token is a common mistake. If you register an async validator under NG_VALIDATORS, Angular treats the returned observable as an error object and the form breaks in confusing ways.
| Aspect | Sync validator | Async validator | Column |
|---|---|---|---|
| Interface | `Validator` | `AsyncValidator` | |
| Provider token | `NG_VALIDATORS` | `NG_ASYNC_VALIDATORS` | |
| Return type | `ValidationErrors \ | null` | `Observable` or `Promise` of that |
| While running | Not applicable | Control status is `PENDING` |
Writing the directive
This directive checks a username against a server endpoint. It waits 400 ms before sending a request, so fast typing doesn't cause a request per keystroke.
import { Directive, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {
AbstractControl,
AsyncValidator,
NG_ASYNC_VALIDATORS,
ValidationErrors,
} from '@angular/forms';
import { Observable, of, timer } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
@Directive({
selector: '[uniqueUsername]',
providers: [
{
provide: NG_ASYNC_VALIDATORS,
useExisting: UniqueUsernameDirective,
multi: true,
},
],
})
export class UniqueUsernameDirective implements AsyncValidator {
private http = inject(HttpClient);
validate(control: AbstractControl): Observable<ValidationErrors | null> {
const value = String(control.value ?? '');
if (!value) {
return of(null);
}
return timer(400).pipe(
switchMap(() =>
this.http.get<{ available: boolean }>('/api/usernames/check', {
params: { name: value },
}),
),
map((res) => (res.available ? null : { usernameTaken: { value } })),
catchError(() => of(null)),
);
}
}Several details in this code matter.
multi: truelets several async validators attach to one control. Angular runs them together and merges their errors.- The empty-value shortcut returns
of(null)so an empty field doesn't cost a request. Leave the "required" rule to therequiredattribute. timer(400)is the debounce. When the value changes, Angular unsubscribes from the previous validator observable before it subscribes to the new one. If the timer hasn't fired yet, the old request never starts. If a request is in flight,HttpClientcancels it on unsubscribe.catchError(() => of(null))treats a network failure as "valid". This is a deliberate choice, covered under the failure modes below.- The observable must complete.
timer(...).pipe(switchMap(http.get))completes becauseHttpClientcompletes after one response. A stream that never completes, such as aSubject, leaves the controlPENDINGforever.
The component must be able to inject HttpClient, so the application needs provideHttpClient() in its providers (for example in app.config.ts).
Using it in a template
Import the directive in the component's imports array and add the attribute to the input.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { UniqueUsernameDirective } from './unique-username.directive';
@Component({
selector: 'app-register',
imports: [FormsModule, UniqueUsernameDirective],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<label for="username">Username</label>
<input
id="username"
name="username"
[(ngModel)]="model.username"
#username="ngModel"
required
minlength="3"
uniqueUsername
/>
@if (username.pending) {
<p role="status">Checking availability...</p>
}
@if (username.errors?.['usernameTaken'] && (username.dirty || username.touched)) {
<p role="alert">That username is taken.</p>
}
<button type="submit" [disabled]="f.invalid || f.pending">Register</button>
</form>
`,
})
export class RegisterComponent {
model = { username: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}The role="status" message is announced politely by screen readers, so users who can't see the form still learn that a check is running. The role="alert" message interrupts, which suits a failure.
Status lifecycle
The diagram shows how a control moves between the three statuses.
Two rules follow from this.
- Async validators run only after all sync validators pass. If
requiredorminlengthfails, the status isINVALIDand no request is sent. This saves server calls and keeps error messages in a sensible order. - A stale result never wins. Because Angular unsubscribes from the older check, a slow response for "ann" can't overwrite the result for "anna".
Gotchas and failure modes
`invalid` is false while pending
A PENDING control is neither valid nor invalid. Both control.valid and control.invalid are false. A button bound only to [disabled]="f.invalid" stays enabled during a check, so a fast user can submit before the answer arrives. Include f.pending as in the example, or use !f.valid.
The check is not a guarantee
A username that was free when the user typed may be taken by the time they submit. Treat the async validator as a convenience for early feedback. The server must still enforce the rule and return a clear error on submit. Map that error back onto the control with username.control.setErrors({ usernameTaken: true }).
Choosing what failure means
The example returns null when the request fails. That keeps users from being locked out during an outage, and it relies on the server check at submit. For rules where a false "valid" is unacceptable, return { checkFailed: true } instead and show a retry message. Decide this per field, not globally.
Request volume
Without a debounce, every keystroke triggers a request. Debouncing with timer solves most of this. You can reduce it further with ngModelOptions, which the previous chapter covered:
<input
name="username"
[(ngModel)]="model.username"
[ngModelOptions]="{ updateOn: 'blur' }"
uniqueUsername
/>With updateOn: 'blur', the model and the validators update only when the field loses focus. That gives one request per visit to the field, and no debounce is needed. The cost is that feedback appears later. Typing-time feedback suits availability hints. Blur suits expensive checks.
Initial value
ngModel writes its initial value asynchronously after the first change detection, and validators run for that value. If you start with a prefilled username, the validator checks it and the control is briefly PENDING. Make sure your pending message and submit button handle that state on first render.
Promises
A Promise works as well as an Observable. A promise can't be cancelled, though. Angular ignores a stale promise result, but the work still runs. Prefer observables for network calls.
Testing the validator
You can test the directive without a form by calling validate directly. Use HttpClientTestingModule-style providers and fakeAsync to control the timer.
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { FormControl } from '@angular/forms';
import { UniqueUsernameDirective } from './unique-username.directive';
describe('UniqueUsernameDirective', () => {
let validator: UniqueUsernameDirective;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
UniqueUsernameDirective,
provideHttpClient(),
provideHttpClientTesting(),
],
});
validator = TestBed.inject(UniqueUsernameDirective);
http = TestBed.inject(HttpTestingController);
});
it('reports usernameTaken when the server says unavailable', fakeAsync(() => {
let result: unknown = 'not-set';
validator.validate(new FormControl('admin')).subscribe((r) => (result = r));
tick(400);
http
.expectOne((req) => req.url === '/api/usernames/check')
.flush({ available: false });
expect(result).toEqual({ usernameTaken: { value: 'admin' } });
http.verify();
}));
});tick(400) advances the fake clock past the debounce, so the request is sent. expectOne finds the request and flush supplies the response. http.verify() fails the test if any unexpected request remains.
Summary of decisions
- Use
NG_ASYNC_VALIDATORSandAsyncValidatorfor checks that need I/O. - Always complete the observable, and debounce inside it with
timerandswitchMap. - Check
pendingin the template, and guard submission withf.pending. - Decide how failures map to validity, and enforce the rule again on the server.
Exercise
A form has a submit button with [disabled]="f.invalid". The username field has an async validator that takes about two seconds. A user types a taken username and clicks Register right away. Why can the form submit, and what is the smallest template change that prevents it?
Show answer
While the async validator runs, the control status is PENDING, and both valid and invalid are false. So f.invalid is false and the button is enabled. Change the binding to [disabled]="f.invalid || f.pending" (or [disabled]="!f.valid"). The server should still re-check the username on submit.
Exercise
Your async validator is validate(c) { return this.http.get<{available: boolean}>(...).pipe(map(r => r.available ? null : { taken: true })); } and it fires a request on every keystroke. Rewrite the return expression so that it waits 500 ms after the last keystroke before sending a request, and explain why this cancels earlier checks.
Show answer
Return timer(500).pipe(switchMap(() => this.http.get<{available: boolean}>(...)), map(r => r.available ? null : { taken: true })). When the control value changes, Angular unsubscribes from the previous validator observable. If its timer hasn't fired, the request never starts. If a request is in flight, HttpClient cancels it on unsubscribe.