【发布时间】:2021-09-13 15:09:46
【问题描述】:
我有一个表单,其中所有字段都是下拉列表并且都是必需的。还有一个条件是两个不同控件之间的值必须相同。我添加了一个自定义验证器来利用跨字段验证,但我遇到的问题是,如果用户使用特殊规则回答问题,它将标记整个表单(FormGroup)有效,即使仍有下拉列表尚未还没摸。
如何在要求所有字段都有值的同时维护跨字段验证?我看到的所有示例都是非常简单的 2 字段表单,它们匹配密码/确认或日期范围。我的表单有大约 30 个字段。
创建动态表单的代码:
questions.forEach(question => {
question.questions.forEach(child => {
group[child.key] = new FormControl({ key: child.value } || '', Validators.required);
});
});
return new FormGroup(group,
[compareValues('26', '27', 'Questions 4 and 5 must have the same answer.')]);
}
自定义验证器:
import { AbstractControl, ValidationErrors, ValidatorFn } from "@angular/forms";
export function compareValues(val1: string, val2: string, message: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const mustMatch1 = control.get(val1);
const mustMatch2 = control.get(val2);
if (mustMatch1 && mustMatch2) {
return mustMatch2.value === '' || mustMatch1.value.key === mustMatch2.value.key ? null : { mustMatch: true, message: message }
}
};
}
【问题讨论】:
-
我还不想回答我自己的问题,因为我需要进行更多测试,但我认为由于我的 FormControl 初始化中的错误,我对验证的工作方式有错误的假设代码。添加以下内容似乎正确设置了初始值,我现在意识到始终将其设置为具有未定义键的对象,该键仍然是有效值,因此是有效形式。
group[child.key] = new FormControl(child.value ? { key: child.value } : '', Validators.required);
标签: angular angular-reactive-forms angular-validation