【问题标题】:Custom validation in Angular template-driven form does not update form stateAngular 模板驱动表单中的自定义验证不会更新表单状态
【发布时间】:2018-08-27 22:14:43
【问题描述】:

我正在尝试为模板驱动的表单编写自定义验证器。验证器本身(包括在下面)就像字段级验证的魅力。但它不会更新整个表单的验证状态。也就是说,当所有控件都有效时,form标签仍然显示class="ng-invalid"。

当我从模板中的控件中删除 phoneValidator 时,一切正常。

我想知道这是否与接口中定义的 registerOnValidatorChange 方法有关。我没有在我的自定义验证器中专门实现这一点,但我也不太确定如何使用它:

export interface Validator {
    validate(c: AbstractControl): ValidationErrors | null;
    registerOnValidatorChange?(fn: () => void): void;
}

想法表示赞赏。谢谢!

文件:phonevalidator.directive.ts:

import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, AbstractControl, ValidationErrors, Validator, FormControl } from '@angular/forms';

@Directive({
  selector: '[validPhoneNumber]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: PhoneValidatorDirective, multi:     true }
  ]
})
export class PhoneValidatorDirective implements Validator {

  validate(control: FormControl): ValidationErrors | null {
    return PhoneValidatorDirective.validatePhone(control);
  }

  static validatePhone(control: FormControl): ValidationErrors | null {

    var regEx = new RegExp(/^[1-9]\d{2}-\d{3}-\d{4}/);

    console.log("Phone validator: validating phone number.")

    var controlValue: string = control.value;

    console.log(regEx.exec(controlValue));

    if (!(regEx.exec(controlValue))) {
      // Return error if phone number is not valid
      console.log('returning false');
      return { phoneNumber: false };
    } else {
      // If no error, return null
      console.log('returning true');
      return { phoneNumber: true };
    }

  }
}

【问题讨论】:

    标签: angular typescript angular6


    【解决方案1】:

    ...看起来这是 Angular 2 form status is always invalid with custom validation for ng-select control 的副本。

    答案是,如果控制是有效的,验证器必须返回 null,而不是 true。

    【讨论】:

      猜你喜欢
      • 2022-07-07
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      相关资源
      最近更新 更多