-
-
Save gearmobile/83de24bbbcea7bebc407b9e4ed59e363 to your computer and use it in GitHub Desktop.
async validation with debounce listening to value change
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 { Component, OnInit } from '@angular/core';'; | |
import { FormBuilder, FormGroup, Validators, AbstractControl, ValidationErrors } from '@angular/forms'; | |
import { Router } from '@angular/router' | |
import { CommonValidators } from '../service/CommonValidator'; | |
import { Response } from '@angular/http'; | |
import { Observable } from 'rxjs/Observable'; | |
import { GlobalService } from '../../shared/service/global.service'; | |
import { AuthHttp } from 'angular2-jwt' | |
declare var $: any; | |
import 'rxjs/add/operator/delay'; | |
import 'rxjs/add/operator/switchMap'; | |
import 'rxjs/add/operator/debounceTime'; | |
import 'rxjs/add/operator/distinctUntilChanged'; | |
@Component({ | |
selector: 'app-sign-up', | |
templateUrl: 'signup.test.component.html', | |
styleUrls: ['./signup.component.css'] | |
}) | |
export class SignUpComponent implements OnInit { | |
registrationForm: FormGroup; | |
isRegistered: boolean = false; | |
errorMessages: any; | |
isLoading: boolean; | |
baseurl: string; | |
emailLoading:boolean; | |
constructor(private http: AuthHttp, private builder: FormBuilder, | |
private global: GlobalService, private router: Router, ) { | |
this.baseurl = global.baseUrl; | |
this.registrationForm = this.builder.group({ | |
username: ['', Validators.required, this.usernameValidation.bind(this)], | |
email: ['', Validators.required, this.emailValidation.bind(this), CommonValidators.email], | |
password: ['', [Validators.required, Validators.minLength(6)]], | |
passwordConfirm: ['', [Validators.required, Validators.minLength(6)]] | |
}, { validator: CommonValidators.matchingPasswords('password', 'passwordConfirm') }); | |
emailValidation(ctr: AbstractControl) { | |
this.emailLoading = true; | |
return ctr | |
.valueChanges | |
.delay(800) | |
.debounceTime(800) | |
.distinctUntilChanged() | |
.switchMap(value => this.http.get(`${this.baseurl}/api/v2/auth/email-availablity/${value}/`)) | |
.map(res => res.json()) | |
.map(res => { | |
this.emailLoading = false; | |
if (res.message === true) { | |
return ctr.setErrors(null); | |
} else { | |
return ctr.setErrors({ emailValidation: 'email already exist' }) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment