Implementing Server‑Side Uniqueness Checks with Angular Async Validators
Learn how to add server‑side uniqueness checks to Angular reactive forms using AsyncValidatorFn, RxJS switchMap for request cancellation, and a reusable validator service that keeps forms responsive.
07 Jun 2026, 01:05 UTC

The problem and the takeaway
When a data‑entry form must guarantee that a value (e‑mail, username, SKU) does not already exist on the server, client‑side validation alone is insufficient. Angular’s AsyncValidatorFn lets you call an HTTP endpoint during the validation pipeline without blocking the UI. The key takeaway: wrap the HTTP call in an Observable, cancel in‑flight requests with switchMap, and return ValidationErrors | null so the form stays responsive and race‑free.
Decision constraints
- Angular 14+ (stable
AsyncValidatorFntyping). - Reactive forms only – template‑driven forms cannot attach async validators declaratively.
- Network latency directly affects perceived responsiveness; keep round‑trip under ~300 ms or add local debounce.
- Server must surface a conflict with HTTP 409 (or a distinct error code) so the validator can emit a specific error key.
Supported options compared
| Approach | How it works | Pros | Cons |
|---|---|---|---|
| Inline async validator in component | Define a method returning AsyncValidatorFn and add it to asyncValidators of a FormControl. |
Quick to prototype; no extra files. | Hard to reuse across components; test setup repeats. |
| Dedicated validator service (recommended) | Injectable service exposing validateUnique(field: string): AsyncValidatorFn; used in any form. |
Reusable, testable, separates HTTP concerns. | Requires provider registration; slight indirection. |
| Directive‑based validator | Attribute directive that registers itself via NG_ASYNC_VALIDATORS. |
Declarative in template; works with template‑driven forms. | More boilerplate; still needs a service for HTTP. |
Trade‑offs
Choosing the dedicated validator service gives the best balance of reuse, testability, and separation of concerns. The inline approach is acceptable for a one‑off form but scales poorly. Directive‑based validators are only justified when you must support template‑driven forms or want a purely template API.
Concrete implementation
1. Generate the validator service
# Run in the Angular workspace root (requires Angular CLI)
ng generate service validators/uniqueness --skip-tests=false
Permission: developer machine with Node ≥ 18 and Angular CLI ≥ 15 installed.
2. Service code (Angular 14+)
import { Injectable } from '@angular/core';
import { AbstractControl, AsyncValidatorFn, ValidationErrors } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable, of, timer } from 'rxjs';
import { map, catchError, switchMap, debounceTime, distinctUntilChanged } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class UniquenessValidatorService {
constructor(private http: HttpClient) {}
/**
* Returns an AsyncValidatorFn that checks uniqueness for the given API endpoint.
* @param endpoint Base URL, e.g. '/api/users/check-email'
* @param paramName Query parameter name the server expects, default 'value'
* @param debounce Milliseconds to wait after user stops typing (default 300)
*/
validateUnique(
endpoint: string,
paramName = 'value',
debounce = 300
): AsyncValidatorFn {
return (control: AbstractControl): Observable => {
if (!control.valueChanges) {
// Called programmatically – skip debounce
return this.check(control.value, endpoint, paramName);
}
return control.valueChanges.pipe(
debounceTime(debounce),
distinctUntilChanged(),
switchMap(value => this.check(value, endpoint, paramName))
);
};
}
private check(value: string, endpoint: string, paramName: string): Observable {
if (!value) return of(null);
const params = { [paramName]: value };
return this.http.get<{ exists: boolean }>(endpoint, { params }).pipe(
map(res => (res.exists ? { unique: true } : null)),
catchError(err => {
// Treat 409 as conflict, other errors as validation‑pending
if (err.status === 409) return of({ unique: true });
return of({ serverError: true });
})
);
}
}
3. Register the validator in a reactive form
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UniquenessValidatorService } from '../validators/uniqueness-validator.service';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
form!: FormGroup;
constructor(
private fb: FormBuilder,
private uniqueness: UniquenessValidatorService
) {}
ngOnInit(): void {
this.form = this.fb.group({
email: [
'',
[Validators.required, Validators.email],
// asyncValidators array – runs after sync validators pass
[this.uniqueness.validateUnique('/api/users/check-email', 'email')]
],
username: [
'',
[Validators.required, Validators.minLength(3)],
[this.uniqueness.validateUnique('/api/users/check-username', 'username', 400)]
]
});
}
onSubmit(): void {
if (this.form.valid) {
// safe to send – async validation already resolved
console.log('Submitting', this.form.value);
}
}
}
4. Template snippet
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div>
<label>Email</label>
<input type="email" formControlName="email" />
<div *ngIf="form.get('email')?.pending">Checking availability…</div>
<div *ngIf="form.get('email')?.errors?.['unique']" class="error">
This e‑mail is already registered.
</div>
<div *ngIf="form.get('email')?.errors?.['serverError']" class="error">
Unable to verify – please try again.
</div>
</div>
<!-- username field analogous -->
<button type="submit" [disabled]="form.invalid || form.pending">Register</button>
</form>
Verification checklist
- Module imports – Ensure
ReactiveFormsModuleandHttpClientModule(orprovideHttpClient()in Angular 15+) are imported in the feature module. - Run the form – Start the dev server (
ng serve) and open the component. - Rapid typing test – Type quickly in the e‑mail field; open the Network tab and confirm that only the latest request remains (previous ones cancelled). The
switchMapin the service guarantees this. - Valid state timing – The submit button should stay disabled while
form.pendingis true. After the server responds,form.validreflects the async result. - Error handling – Simulate a 409 response (e.g., via a mock interceptor) and verify the
uniqueerror appears. Simulate a 500 and verifyserverErrorshows.
Limitations & practical checks
- Latency ceiling – If the API regularly exceeds 500 ms, consider a longer debounce or a local cache of recent checks.
- Race conditions – The
switchMapcancels prior requests, but only if the control’svalueChangesobservable is used. ProgrammaticsetValuebypasses the debounce; the service falls back to an immediate check. - Server contract – The validator expects a JSON payload
{ exists: boolean }or a 409 status. Adjustcheck()if your API differs. - Testing – Unit‑test the service with
HttpTestingControllerto assert request cancellation and error mapping.
How to confirm it works in production
Add a lightweight telemetry event when form.pending transitions to false and log the elapsed time. If the 95th‑percentile exceeds your UX budget, increase debounce or optimise the endpoint.
Diagram labels
- User input → valueChanges
- debounceTime / distinctUntilChanged
- switchMap → HTTP GET
- ValidationErrors → FormControl status
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.