【问题标题】:How to enforce required validation on all form controls when using cross-field validation with Angular Reactive Forms使用 Angular Reactive Forms 进行跨字段验证时,如何对所有表单控件强制执行所需的验证
【发布时间】: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


【解决方案1】:

正如我在上面的评论中提到的,由于我在 FormControl 初始化中的一个错误,这是验证过程中的一个误解。

原来 FormControl 总是有一个有效值。即使 child.value 未定义或为空字符串,也总会有一个设置了键的对象,这仍然被认为是我如何进行此设置的有效条目。

以下是我所做的更改,它清理了验证,并且我让它按照我的预期工作。

改变以前的:

  questions.forEach(question => {
    question.questions.forEach(child => {
      group[child.key] = new FormControl({ key: child.value } || '', Validators.required);
    });
  });

以下内容:

  questions.forEach(question => {
    question.questions.forEach(child => {
      group[child.key] = new FormControl(child.value ? { key: child.value } : '', Validators.required);
    });
  });

【讨论】:

    猜你喜欢
    • 2017-03-10
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 2014-10-08
    相关资源
    最近更新 更多