【发布时间】:2022-11-22 19:49:58
【问题描述】:
所以我的问题是。我有一个非常大的表格来填写 200+ 个输入字段,我需要一个字段(标题),但我也想检查他们是否至少填写了一个其他字段。哪一个都无所谓。但是一旦满足该要求,他们就可以提交表格。
【问题讨论】:
标签: angular forms validation
所以我的问题是。我有一个非常大的表格来填写 200+ 个输入字段,我需要一个字段(标题),但我也想检查他们是否至少填写了一个其他字段。哪一个都无所谓。但是一旦满足该要求,他们就可以提交表格。
【问题讨论】:
标签: angular forms validation
将验证器添加到 FormGroup 以检查所有输入。
new FormGroup(
{
requiredControl: new FormControl(initialValue, [Validators.required]),
control1: new FormControl(...),
...
control200: new FormControl(...)
},
[someValueValidator()]
)
private someValueValidator() {
return (controls: AbstractControl) => {
// check if any non-required control is set then return null,
// otherwise return ValidationError
}
}
【讨论】:
这很简单,请参阅Stackblitz 示例。您只需要为一个字段设置一个验证器,然后检查 onSubmit 所有其他字段值:
onSubmit(): void {
let anyOtherControlIsFilled = false;
Object.keys(this.form.controls).forEach((key) => {
if (!this.form.controls[key].validator) {
if (
this.form.controls[key].value !== null &&
this.form.controls[key].value !== ''
) {
console.log('Passt');
anyOtherControlIsFilled = true;
}
}
});
if (this.form.valid && anyOtherControlIsFilled) {
this.submitted = true;
alert('All ok');
} else {
this.submitted = true;
alert('Error');
return;
}
console.log(JSON.stringify(this.form.value, null, 2));
}
问候,弗洛
【讨论】: