Angular 5 AsyncValidator离开状态为:PENDING的控制

时间:2018-07-31 17:16:38

标签: angular forms rxjs

我无法在Reactive Form上成功使用AsyncValidator函数,需要帮助以了解原因。

验证器功能是:

export function checkVoiceNumberExists(): AsyncValidatorFn {
    return (c: AbstractControl): Observable<ValidationErrors | null> => {
        return (c.value === null) ? Observable.of(null) : ValidMobileNumbers.checkVoiceNumberExists(c.value)
            .map(results => {
                return Observable.of(results.length === 1 ? null
                    : { 'invalidMobileNotListed': 'This mobile number does not exist in the validation list' }
                );
            }
            );
    }
}

我的打字稿表格组件导入并使用以下功能:

import { checkVoiceNumberExists, checkVoiceNumberNotAllocated } from 'common/validators/company-mobile-numbers';

let fctrl_voice: FormControl = new FormControl(
    '',
    [SabreFormControlValidators.hasLeadingZero, SabreFormControlValidators.isTelephoneNumber],
    [checkVoiceNumberExists(), checkVoiceNumberNotAllocated(empID)]
);

我看到在以下调试输出中应该返回错误:

Object {invalidMobileNotListed: "This mobile number does not exist in the validatio…"}
invalidMobileNotListed:"This mobile number does not exist in the validation list"

但是,表单控件的状态仍保持为PENDING,如下所示:

<input _ngcontent-c9="" class="form-control ng-dirty ng-pending ng-touched" maxlength="11" ng-reflect-maxlength="11" ng-reflect-name="emp_telno_company" id="emp_telno_company">

我希望看到ng-invalid而不是ng-pending

由于这个问题

  • 我的CSS错误类未应用于控件
  • 状态STATUS显示为PENDING

我尝试对验证器功能进行较小的改动,如下所示:

export function checkVoiceNumberExists(): AsyncValidatorFn {
    return (c: AbstractControl): Observable<ValidationErrors | null> => {
        return (c.value === null) ? Observable.of(null) : ValidMobileNumbers.checkVoiceNumberExists(c.value)
            .map(results => {
                return results.length === 1 ? null : { 'invalidMobileNotListed': 'This mobile number does not exist in the validation list' };
            });
    }
}

在这种情况下我该怎么做才能正确接收验证错误?

0 个答案:

没有答案