Sub topic 16
Server-Side Checks with Async Validators
This chapter assumes you already know how to write a synchronous ValidatorFn, read touched and error state in a template, and use RxJS operators like map, switchMap, and catchError. You also need provideHttpClient() registered in your application config for the HTTP example.
Some rules can only be checked by a server. Examples are "this username is free", "this coupon code exists", and "this email is not already registered". An async validator handles these checks. It returns an Observable or Promise that eventually produces either null (valid) or a ValidationErrors object.
The AsyncValidatorFn Contract
An async validator has this signature:
type AsyncValidatorFn = (
control: AbstractControl
) => Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;Angular enforces some rules on how it runs:
- Async validators run only after all synchronous validators pass. If
Validators.requiredfails, no request is sent. - While the check is running, the control's
statusis'PENDING', andpendingistrue. - When the value changes again, Angular unsubscribes from the previous validator observable before starting a new one. An HTTP request still in flight is cancelled.
- The observable must complete. Angular waits for completion before applying the result.
A Service and a Validator Factory
Keep the HTTP call in a service and pass it into a factory function. That way the validator stays a plain function you can test with a fake.
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AbstractControl, AsyncValidatorFn, ValidationErrors } from '@angular/forms';
import { Observable, of, timer } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
export interface UsernameChecker {
isTaken(username: string): Observable<boolean>;
}
@Injectable({ providedIn: 'root' })
export class UsernameService implements UsernameChecker {
private http = inject(HttpClient);
isTaken(username: string): Observable<boolean> {
return this.http
.get<{ taken: boolean }>('/api/usernames/check', { params: { username } })
.pipe(map((res) => res.taken));
}
}
export function usernameAvailable(checker: UsernameChecker, delayMs = 300): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> =>
timer(delayMs).pipe(
switchMap(() => checker.isTaken(control.value)),
map((taken) => (taken ? { usernameTaken: true } : null)),
catchError(() => of(null)),
);
}The timer(delayMs) at the start debounces the check. Every keystroke starts a new validator run, and Angular unsubscribes from the old one. A timer that hasn't fired yet gets cancelled, so the request goes out only once the user pauses for delayMs. Putting debounceTime inside the validator would do nothing, because each run gets a fresh observable that emits only once.
Attaching It to a Control
Pass async validators through the asyncValidators option, separate from validators:
import { Component, inject } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { UsernameService, usernameAvailable } from './username-available.validator';
@Component({
selector: 'app-signup',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<label>
Username
<input formControlName="username" />
</label>
@if (username.pending) {
<p>Checking availability…</p>
}
@if (username.hasError('usernameTaken')) {
<p>That username is already taken.</p>
}
@if (username.touched && username.hasError('required')) {
<p>Username is required.</p>
}
<button type="submit" [disabled]="form.invalid || form.pending">Sign up</button>
</form>
`,
})
export class SignupComponent {
private checker = inject(UsernameService);
form = new FormGroup({
username: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
asyncValidators: [usernameAvailable(this.checker)],
}),
});
get username() {
return this.form.controls.username;
}
onSubmit(): void {
console.log(this.form.getRawValue());
}
}The submit button checks form.pending as well as form.invalid. A pending form is not invalid, so [disabled]="form.invalid" alone would let the user submit before the check finishes.
The usernameTaken message doesn't need a touched guard. The error only appears after a server round trip, which happens only after the user has typed something.
How Status Moves During a Check
| Moment | `status` | `pending` | `invalid` | `errors` |
|---|---|---|---|---|
| Sync validator fails | `INVALID` | `false` | `true` | `{ minlength: ... }` |
| Async check in flight | `PENDING` | `true` | `false` | `null` |
| Server says taken | `INVALID` | `false` | `true` | `{ usernameTaken: true }` |
| Server says free | `VALID` | `false` | `false` | `null` |
Pending status bubbles up. If any child is pending, the parent FormGroup is pending too.
Common Errors
The control stays PENDING forever. The observable never completed. This happens when a validator returns something like store.select(...), a Subject, or another control's valueChanges. Add take(1) or first() to fix it.
A request fires on every keystroke. The validator calls the service directly with no timer. Add the timer, or set updateOn: 'blur' on the control so validation runs less often. The next chapter covers updateOn.
Validation runs on load or on patchValue. Any value update, including programmatic ones, runs the validators again. When you load an existing profile, the user's own username will be reported as taken. Handle this in the validator by skipping the check when control.value equals the original value. You can also pass { emitEvent: false }, but that suppresses only the events. The validation itself still runs.
The validator was created inside the template or a getter. Each call creates a new function, and the control never sees a stable validator. Create the validator once, when you build the control.
Group-level async validators. You can attach asyncValidators to a FormGroup to check a combination of fields on the server. The same rules apply. Group async validators run only after every child and the group's own sync validators pass.
Exercise
A teammate disables the submit button with [disabled]="form.invalid" and says async validation is broken because users can submit a taken username. What is happening, and what is the fix?
Show answer
While the async check is running, the form's status is PENDING, so invalid is false. Users who click during that window can submit. Disable the button with form.invalid || form.pending. The server must also reject duplicates on submit.
Exercise
Why does timer(300).pipe(switchMap(...)) debounce requests inside an async validator, while debounceTime(300) applied to the returned observable does not?
Show answer
Angular creates a new validator observable for each value change and unsubscribes from the previous one. A pending timer is cancelled before it fires, so only the last run reaches the server. debounceTime acts on emissions within a single stream. Each validator run is a separate stream, so nothing gets debounced.
Exercise
An edit-profile form loads the user's data with patchValue, and the username field immediately shows "already taken". Explain the cause and give one fix.
Show answer
patchValue runs validators again, so the async validator checks the user's current username against the server, and the server reports it as taken by that same user. Pass the original username to the validator factory and return of(null) when control.value equals it. Alternatively, have the endpoint exclude the current user from the check.