我正在构建一个Angular 5表单。我要求在表格(电子邮件或电话)上提供联系信息。电子邮件地址或电话号码是必需的,但不是两者都需要。如何为此方案创建自定义验证器?从docs看来,验证器只负责一个控件,而我的验证器需要知道多个控件来检查它们的所有值。
ngOnInit() {
this.form = this.formBuilder.group({
'name': [null, [Validators.required]],
'email': [null, []], // A user can provide email OR phone, but
'phone': [null, []], // both are not required. How would you do this?
});
}
答案 0 :(得分:4)
一种可能的解决方案是声明一个函数,该函数将表单本身作为参数,例如:
export function emailAndPhone() {
return (form: FormGroup): {[key: string]: any} => {
return (form.value.phone && form.value.email) ||
(!form.value.phone && !form.value.email)
? { emailAndPhoneError : true }
: null;
};
}
使用validator
extras:
ngOnInit() {
this.form = this.formBuilder.group({
'name': [null, [Validators.required]],
'email': [null, []], // A user can provide email OR phone, but
'phone': [null, []], // both are not required. How would you do this?
}, { validator: emailAndPhone() });
}
如果您需要识别验证何时检测到无效输入,请确保表单错误列表中存在先前定义的emailAndPhoneError
。喜欢这个
*ngIf="myForm.hasError('emailAndPhoneError')" //true means invalid