0
votes

I am trying to create a control with async validation and I don't want sync validation:

Creating form using formBuilder.

  this.myForm = this.fb.group({ 
    someControl: new FormControl(
        "",
        null,
        [this.valueUnique.bind(this)]
      )})

If I keep sync validation parameter as Validators.required then I get no error.

Error:

ERROR Error: Expected validator to return Promise or Observable. at toObservable (forms.js:603) at Array.map () at FormControl.asyncValidator (forms.js:591) at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runAsyncValidator (forms.js:2535) at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl.updateValueAndValidity (forms.js:2508) at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._updateTreeValidity (forms.js:2523) at forms.js:2522 at forms.js:3309 at Array.forEach () at FormGroup.push../node_modules/@angular/forms/fesm5/forms.js.FormGroup._forEachChild (forms.js:3309)

Validator function:

 /**
   * Validator to checking existance/uniqueness
   * of entered value
   * @param control
   */
   valueIsUnique(control: AbstractControl): Promise<ValidationErrors|null> | null {
    if (control && (control.value !== null && control.value !== undefined)) {
      return new Promise((resolve, reject) => {
        this.service.checkValueExists(control.value).subscribe(res => {
         {
            if (res && res['data']) {
              resolve({
                unique: true
              });
            }
              else {
                resolve(null);
            }
           }
          },
            err=>
          {
            resolve(null);
          });
    });
  }
  }
1
Are you sure that this.valueUnique.bind(this) is returning an Observable or Promise? Because hat is what the error says, your binding to the function valueUnique is not returning this type. - Sam Vloeberghs
@SamVloeberghs thanks, yes my async validator returning promise. I have updated question. Also added similar post yesterday: stackoverflow.com/questions/55375700/… If I add sync validation = Validators.required then error does not come. - Alwaysalearner
your if should be inside the return new Promise. You have a potential case here that you are not return a promise. - Sam Vloeberghs
@SamVloeberghs Ok thanks. Let me check and I will update you. - Alwaysalearner
@SamVloeberghs How can I return promise in that If conditione it is outside new promise? - Alwaysalearner

1 Answers

1
votes

This question is a bit old but maybe my answer could be useful.

I tried this way and it worked.

archivos: [null, [] , mimeType],

It only worked if i put the square brackets for sync validators and don´t put them for async validator.