Sub topic 14
Asynchronous validation
This chapter assumes you know the built-in validators, error display, and the custom validator directive from earlier chapters. It adds checks that need to wait for something, such as a server call.
How async validation works
A synchronous validator returns its result immediately. An asynchronous validator returns an Observable (or a Promise) that produces the result later. The result has the same shape as a sync validator's: null when valid, or an error object when invalid.
Angular runs async validators only after every synchronous validator passes. While the async check is running, the control's status is PENDING. When a new value arrives, Angular unsubscribes from the previous check, so a stale response cannot overwrite a newer one.
Writing the validator directive
An async validator directive implements AsyncValidator and registers under NG_ASYNC_VALIDATORS, not NG_VALIDATORS. This example checks a username against a service. The service is simulated here, so the code runs without a backend.
import { Directive, Injectable, inject } from '@angular/core';
import {
AbstractControl,
AsyncValidator,
NG_ASYNC_VALIDATORS,
ValidationErrors,
} from '@angular/forms';
import { Observable, of, timer } from 'rxjs';
import { delay, map, switchMap } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class UsernameService {
private taken = ['admin', 'root', 'kiro'];
isTaken(name: string): Observable<boolean> {
return of(this.taken.includes(name.toLowerCase())).pipe(delay(300));
}
}
@Directive({
selector: '[uniqueUsername]',
standalone: true,
providers: [
{ provide: NG_ASYNC_VALIDATORS, useExisting: UniqueUsernameDirective, multi: true },
],
})
export class UniqueUsernameDirective implements AsyncValidator {
private service = inject(UsernameService);
validate(control: AbstractControl): Observable<ValidationErrors | null> {
return timer(400).pipe(
switchMap(() => this.service.isTaken(String(control.value ?? ''))),
map((taken) => (taken ? { uniqueUsername: true } : null)),
);
}
}The timer(400) works as a debounce. Angular unsubscribes when the user types again, so the service is called only after 400 ms without typing.
Using it in a template
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { UniqueUsernameDirective } from './unique-username.directive';
@Component({
selector: 'app-username',
imports: [FormsModule, UniqueUsernameDirective],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<input name="username" [(ngModel)]="model.username"
#u="ngModel" required minlength="3" uniqueUsername />
@if (u.pending) {
<p>Checking availability…</p>
}
@if (u.errors?.['uniqueUsername']) {
<p role="alert">That username is taken.</p>
}
<button type="submit" [disabled]="f.invalid || f.pending">Save</button>
</form>
`,
})
export class UsernameComponent {
model = { username: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}Common errors
- Observable never completes. Angular waits for completion. An open stream such as a
Subjectleaves the control inPENDINGforever. Usetake(1)or an HTTP call, which completes by itself. - Submitting while pending.
f.invalidisfalseduringPENDING, so a button disabled only byf.invalidstays enabled mid-check. Also testf.pending. - Registering under
NG_VALIDATORS. Angular then treats the return value as a sync result and the check never works. UseNG_ASYNC_VALIDATORS. - Throwing on server failure. An error in the stream stops validation. Catch it with
catchError(() => of(null))if you would rather let the server reject the final submit. - Calling the server on every keystroke. Debounce as shown, or set
[ngModelOptions]="{ updateOn: 'blur' }"to validate only when the field loses focus.
Exercise
A field uses required and an async validator. The user clears the field. Does the async validator run, and why?
Show answer
No. Angular runs async validators only when all sync validators pass. The empty value fails required, so the control becomes INVALID with a required error and the service is not called.