-
-
Save deusmar/af45fa8483bb5f7b69439b8dbf079406 to your computer and use it in GitHub Desktop.
AsyncValidatorFn Angular 7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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