且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么Angular 4 FormGroup自定义验证器不起作用?

更新时间:2022-12-10 17:29:50

验证函数不应在控件上设置错误.他们应该返回验证错误对象.

Validation functions aren't supposed to set errors on controls. They're supposed to return validation error objects.

formValidator(): ValidatorFn {
    return (group: FormGroup): ValidationErrors => {
        // use the abstraction provided by the framework
        const control1 = group.get('control1');
        const control2 = group.get('control2');
        // return the correct value depending on your condition
        return control1.value === 'ABC' && control2.value !== 'ABC' ? 
          { invalidData: true } : null;
    };
}