Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Custom Async Validator in Angular2/4/5

1. Is it even supported by Angular yet ? see this open issue

2. If it is, then what is wrong in the code below

export class someClass{      myForm:ControlGroup;      constructor(public http:Http, public formBuilder:FormBuilder)        this.myForm = formBuilder.group({             ImageId: ["", Validators.required, this.asynValidator]     });      asyncValidator(control: Control): {[key: string]: any} {          return new Promise (resolve => {            let headers = new Headers();           headers.append('Content-Type', 'application/json');            this.http.get('http://localhost/ImageIdValidate?id='+ control.value, {headers:headers})                 .map(res => res.json())                 .subscribe(data => {                     console.log(data);                     if(data != null) {                         resolve({"duplicate": true})                     }                     else resolve(null);                       })             });         });       }     } 

It doesn't even make a server request.

like image 907
Ankit Singh Avatar asked Feb 20 '16 09:02

Ankit Singh


2 Answers

You need to bind your method on the component instance itself as described below:

this.myForm = formBuilder.group({             ImageId: ["",                    Validators.required,                 this.asynValidator.bind(this)]     }); 

Otherwise you won't be able to use the http property to execute your request.

This article could also give you some hints about asynchronous form validation (see the section "asynchronous validation"):

  • http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/
like image 95
Thierry Templier Avatar answered Oct 11 '22 11:10

Thierry Templier


as of newer versions of Angular, but pre version 5.0.0 you would add the async validator as the third argument for your formcontrol:

myControl: ['', [Validators.required], [this.asyncValidator.bind(this)]] 

since version 5.0.0 you can now mark the validators like so:

myControl: ['', {validators: [Validators.required],                   asyncValidators:[this.asyncValidator.bind(this)]}] 
like image 33
AT82 Avatar answered Oct 11 '22 10:10

AT82