-
-
Save ellipizle/4a7a87f2b0e31e71bf7cfdc235335328 to your computer and use it in GitHub Desktop.
Username validator
This file contains hidden or 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 { FormControl } from '@angular/forms'; | |
import { AsyncValidatorFn, ValidatorFn } from '@angular/forms/src/directives/validators'; | |
import { Control } from '@angular/common'; | |
import { Injectable } from '@angular/core'; | |
import { Http } from '@angular/http'; | |
import { Observable } from 'rxjs/Observable'; | |
import { ReplaySubject } from 'rxjs/ReplaySubject'; | |
import { API_USER_URL } from '../services/constants'; | |
@Injectable() | |
export class UsernameValidator { | |
input: ReplaySubject<any>; | |
request: any; | |
constructor(private http: Http) { | |
this.input = new ReplaySubject(1); | |
this.request = this.input | |
.debounceTime(50) | |
.distinctUntilChanged() | |
.take(1) | |
.switchMap(input => this.http.get(`${API_USER_URL}/checkUsername?username=${input}`)) | |
.map(r => r.json()) | |
.catch(() => Observable.of(null)); | |
} | |
usernameTaken = (control: FormControl): AsyncValidatorFn => { | |
this.input.next(control.value); | |
return this.request; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment