我想知道如何在Angular2中使用控制组中的OR语句进行组合验证。例如,我有三个输入字段,我想要1需要,另外两个需要与OR一样。 [输入名称] =必填,([输入电子邮件]或[输入电话])=必填。
this.userForm = this._formBuilder.group({
'name': ['', Validators.required],
'email': ['', Validators.compose([Validators.required, ValidationService.emailValidator]),
'phone': ['', Validators.required]]
});
答案 0 :(得分:2)
group方法采用第二个参数,您可以在其中定义自定义验证函数。这在验证规则取决于一个或多个其他字段的状态的情况下非常有用。
this.userForm = this._formBuilder.group({
'name': ['', Validators.required],
'email': ['', Validators.compose([Validators.required, ValidationService.emailValidator]),
'phone': ['', Validators.required]
}, { validator: this.oneRequired('email', 'phone') });
oneRequired(first:string, second:string) {
return (group: ControlGroup) => {
var control1 = group.controls[first];
var control2 = group.controls[second];
var a = Validators.required(control1) || { required: false };
var b = Validators.required(control2) || { required: false };
if (a['required'] && b['required']) {
control1.setErrors({ oneRequired: true });
control2.setErrors({ oneRequired: true });
}
else {
control1.setErrors(null);
control2.setErrors(null);
}
};
}