Skip to content

Instantly share code, notes, and snippets.

@deusmar
Last active February 3, 2022 15:28
Show Gist options
  • Save deusmar/af45fa8483bb5f7b69439b8dbf079406 to your computer and use it in GitHub Desktop.
Save deusmar/af45fa8483bb5f7b69439b8dbf079406 to your computer and use it in GitHub Desktop.
AsyncValidatorFn Angular 7
import { AbstractControl, AsyncValidatorFn, ValidationErrors } from '@angular/forms';
import { UserService } from '../services/user.service';
import { Observable } from 'rxjs/Observable';
import { catchError, map, switchMap } from 'rxjs/operators';
import { of, timer } from 'rxjs';
export function uniqueUsernameValidator(userService: UserService): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
return timer(500).pipe(switchMap(() => {
if (!control.value) {
return of(null);
}
return userService.isUsernameUnique(control.value).pipe(
map(isUnique => (isUnique ? null : {usernameNotUnique: true})),
catchError(() => null)
);
}));
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment