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.

Revisions

  1. qdouble created this gist Jul 13, 2016.
    30 changes: 30 additions & 0 deletions Username Validation
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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;
    }
    }