angular - Angular2 username or email taken async validation -
i need implement async validation github api. hope me.
export class usernamevalidator { static usernametaken(control: formcontrol): promise<validationresult> { return new promise((resolve, reject) => { settimeout(() => { //how can use github api this: // if (control.value === "this._http.get('http://api.github.com/users/'+this.username)")) { if (control.value === "david") { console.log('username taken') resolve({"usernametaken": true}) } else { resolve(null); }; }, 1000); }); } }
thank you.
this implemented within reactive form, should modifiable solution form driven method.
the validator given service actual via api (a 404 returned if given user not exist):
export function usernametaken(httpservice: httpservice) { return control => new promise((resolve, reject) => { console.log("in validator"); //how can use github api this: httpservice.lookupuser(control.value).subscribe(data => { console.log(data); if(data.id) { resolve({ usernametaken : true}) } else { resolve(null); } }, (err) => { console.log("in error"+ err); if(err !== "404 - not found") { resolve({ usernametaken : true}); } else { resolve(null); } }); }); }
the service looks this:
@injectable() export class httpservice { constructor(private http: http) {} lookupuser(username: string): observable<any> { return this.http.get("https://api.github.com/users/" + username) .map(this.extractdata) .catch(this.handleerror) observable<any>; }; <...> }
and inject in service , apply validator (third spot in array asyncvalidators:
constructor(private fb: formbuilder, private httpservice: httpservice) { this.name = 'angular2', this.form = this.fb.group({ username: ['', validators.required, usernametaken(this.httpservice)] });
with actual input looking pretty normal:
<input type="text" placeholder="username" formcontrolname="username"/>
here's plunker demonstrating usage of async validator: http://plnkr.co/edit/19lp0e9x6l4kpyx0org0?p=preview
Comments
Post a Comment