如何以编程方式验证反应式表单控件?

How can I validate reactive form controls programmatically?

我有一个 FormGroup 反应形式的对象。现在我想以编程方式触发表单验证。

我已经用这段代码检查了表单,但是我的控件 css 状态 类 没有设置,就像我单击控件并在控件外部单击时完成的那样。

if (!this.formGroup.valid) {
  // TODO: Fix that invalid controls don't get highlighted
  return;
}

您可以使用以下代码以编程方式触发验证器。

this.formGroup.controls['controlNameHere'].markAsTouched();

当您创建反应式表单时,您隐含地表示该表单应根据特定策略更新其值和有效性。

有 3 种策略:

  • 模糊
  • 变化中
  • 提交时

您可以在创建表单控件或表单组时更改更新策略。在您的情况下,变更策略应该有效。

Here is a stackblitz 包含两种策略,看看哪种最适合您。

first = new FormControl('', {
  validators: [Validators.minLength(3)],
  updateOn: 'blur'
})
second = new FormControl('', {
  validators: [Validators.minLength(3)],
  updateOn: 'change'
})

验证所有表单域

validateAllFormFields(formGroup: FormGroup) {
  Object.keys(formGroup.controls).forEach(field => {
    const control = formGroup.get(field);

    if (control instanceof FormControl) {
      control.markAsTouched({ onlySelf: true });
    } 
    else if (control instanceof FormGroup) {
      this.validateAllFormFields(control);
    }
  });
}