Skip to content

Instantly share code, notes, and snippets.

@qdouble
Created July 13, 2016 02:42
Show Gist options
  • Save qdouble/388b09aa3dea96f40a1680e536e013f2 to your computer and use it in GitHub Desktop.
Save qdouble/388b09aa3dea96f40a1680e536e013f2 to your computer and use it in GitHub Desktop.
Username validator
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