How to add async validation without adding any other validators?

此生再无相见时 提交于 2019-12-11 17:13:59

问题


I am using angular 7, reactive form.

I have a requirement to check the existence of particular value on the server to make field valid/invalid.

Component Class:

Control:

  valueControl = new FormControl("" ,Validators.required,
  ), [this.valueIsUnique.bind(this)]);



  /**
   * 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, this.organizationId).subscribe(res => {
         {
            if (res && res['data']) {
              resolve({
                unique: true
              });
            }
              else {
                resolve(null);
            }
           }
          },
            err=>
          {
            resolve(null);
          });
    });
  }
  }



**Service:**

  checkValueExists(value:string) {
     return this._http.get(`${API}/${value}/exists`, {
      headers: ...
    }
    );
  }

Now this works fine. But I don't want to make control mandatory i.e Validators.required. So as a hack I added Validators.minLength(1) as sync validation but that gives error:

ERROR Error: Expected validator to return Promise or Observable. at toObservable (forms.js:603) at Array.map () at forms.js:591 at forms.js:611 at Array.map () at _executeAsyncValidators (forms.js:611) 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 FormControlDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormControlDirective.ngOnChanges (forms.js:4463)

Is there are way to add async validation without having to add sync validation as second parameter:

Took reference from this SO ques/ans

来源:https://stackoverflow.com/questions/55375700/how-to-add-async-validation-without-adding-any-other-validators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!