Shahar Shokrani
Shahar Shokrani

Reputation: 8740

FormControl: async validator does not triggered to validate non valid input

I'm trying to implement a remote-server-validator using a Promise, but the text input does not being triggered.

`app.component.html'

<form [formGroup]="myForm">
  Foo: <input type="text" formControlName="foo">
  <span *ngIf="!myForm.get('foo').valid">Not valid foo</span>
</form>

'app.component.ts'

ngOnInit() {    
  this.myForm = new FormGroup({
    'foo': new FormControl(null, [Validators.required, this.validateAsync.bind(this)])
  }); 
}

validateAsync(control: FormControl): Promise<any> | Observable<any> {
    const promise = new Promise<any>((resolve) => {
        //post the control.value and check for the response value: fooIsValid
        if (fooIsValid)
            resolve(null); 
        else
            resolve({'FooRuleValidation': true});
    });
    return promise;
}

What I'm doing wrong? I've noticed that it makes the required not to work as well.

Upvotes: 0

Views: 71

Answers (1)

Chellappan வ
Chellappan வ

Reputation: 27293

You need to pass async validator function as a third argument

Try this:

this.myForm = new FormGroup({
    'foo': new FormControl(null, [Validators.required],[this.validateAsync.bind(this)])
 }); 

Upvotes: 1

Related Questions