【发布时间】: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