javascript / intermediate
Snippet
Implementing Custom Async Validators
Async validators are essential for tasks like checking username availability against a server. They return an Observable or Promise that eventually emits validation errors or null.
snippet.js
1
2
3
4
5
6
7
8
9
10
import { AbstractControl, ValidationErrors } from '@angular/forms';import { Observable, of } from 'rxjs';import { delay, map } from 'rxjs/operators';export function checkUnique(control: AbstractControl): Observable<ValidationErrors | null> {return of(control.value).pipe(delay(1000),map(val => (val === 'taken' ? { exists: true } : null)));}
angular
Breakdown
1
export function checkUnique(control: AbstractControl): Observable<ValidationErrors | null>
Defines a function that takes a control and returns an Observable of errors.
2
return of(control.value).pipe(
Creates an observable stream from the current control value.
3
delay(1000),
Simulates network latency by waiting for one second.
4
map(val => (val === 'taken' ? { exists: true } : null))
Maps the value to an error object if it matches 'taken', otherwise null.