Sub topic 15
Server-Side Checks with Async Validators
This chapter assumes you can already write a synchronous ValidatorFn, attach validators to a FormControl, and read hasError() in a template. It also assumes you know basic RxJS operators such as map and catchError.
Some rules can only be checked by the server. Whether a username is already taken is a common case. An async validator handles these checks. It returns an Observable or a Promise that later emits either null or a ValidationErrors object.
The Shape of an AsyncValidatorFn
An AsyncValidatorFn receives the control and returns Observable<ValidationErrors | null>. A factory function lets you pass in the service that does the lookup. Defining that service as an interface keeps the validator easy to test.
import { AbstractControl, AsyncValidatorFn, ValidationErrors } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
export interface UsernameChecker {
isTaken(username: string): Observable<boolean>;
}
export function usernameAvailable(checker: UsernameChecker): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> =>
checker.isTaken(control.value).pipe(
map((taken) => (taken ? { usernameTaken: true } : null)),
catchError(() => of(null)),
);
}The catchError makes a failed request count as "no error", so a network problem doesn't lock the user out of the form. If you would rather show the failure, return an error key such as { usernameCheckFailed: true } instead.
Attaching It and Showing Pending State
Async validators go in the asyncValidators option, separate from validators:
import { Component, Injectable, inject } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
import { UsernameChecker, usernameAvailable } from './username-available.validator';
@Injectable({ providedIn: 'root' })
export class FakeUsernameService implements UsernameChecker {
private taken = ['admin', 'angular'];
isTaken(username: string): Observable<boolean> {
return of(this.taken.includes(username.toLowerCase())).pipe(delay(500));
}
}
@Component({
selector: 'app-username-field',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<input [formControl]="username" placeholder="Username" />
@if (username.pending) {
<p>Checking availability…</p>
}
@if (username.hasError('usernameTaken')) {
<p>That username is taken.</p>
}
`,
})
export class UsernameFieldComponent {
username = new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
asyncValidators: [usernameAvailable(inject(FakeUsernameService))],
});
}How Angular Runs Them
The async validators run only after every sync validator passes. This way a two-letter value never reaches the server. While a check is in flight, status is 'PENDING' and pending is true. The parent group is also PENDING, so form.invalid is false during the check. Disable the submit button with form.invalid || form.pending.
If the value changes while a check is still running, Angular unsubscribes from the old observable and starts a new one. Stale responses therefore never win. The validator still fires on every keystroke, though. To cut down on requests, delay the update with updateOn: 'blur', which the next chapter covers.
Common Errors
| Symptom | Cause |
|---|---|
| Control stays `PENDING` forever | The observable never completes |
| Async validator never runs | A sync validator is failing first |
| Submit enabled during the check | Only `invalid` is checked, not `pending` |
| Validator in the `validators` array | Angular treats the returned observable as an error object |
Exercise
A user types "ad" into the username field above. Does FakeUsernameService.isTaken get called, and what is the control's status?
Show answer
No. Validators.minLength(3) fails, so Angular skips the async validator. The status is 'INVALID' with a minlength error, and the status never becomes 'PENDING'.
Exercise
You build an async validator from this.otherControl.valueChanges.pipe(map(...)), and the control never leaves PENDING. Why, and how do you fix it?
Show answer
valueChanges never completes, and Angular waits for the observable to complete before it settles the status. Add take(1) (or first()) so the stream completes after one emission.