首页 > 解决方案 > FormArray 的垂直自定义验证器

问题描述

我希望总数精确到 100。但是这个验证器不起作用。我的代码有什么问题?

export class CustomValidators { 
  public static verticalTotal(total: number, refControl: string) {
    return (control: FormArray): ValidationErrors | null => {
      const arrayValue = control.value || [];
      let actualTotal = 0;
      control.controls.forEach(ctrl => {
        actualTotal += +(ctrl.get(refControl).value);
     });
  return actualTotal !== total ?
     { verticalTotal: true,
       message: `Total should be ${total}, not ${actualTotal}`
     } : null;
    };
   } 
}

我像这样应用验证器

 this.itemForm = this.fb.group({
  subsidiaries: this.fb.array([], {
    validators: [CustomValidators.verticalTotal(100, 'percent')]
  })
}, { validators: [] });

const line = this.fb.group({
  'name': ['', []],
  'percent': [0, []]
});
(this.itemForm.get('subsidiaries') as FormArray).push(line);

this.itemForm.get('subsidiaries').updateValueAndValidity();

标签: angularangular-reactive-formsangular-validation

解决方案


谢谢@Eliseo,你是对的。我的代码有效。除了我返回的对象不包含消息的定义。它必须是

   {
    verticalTotal: { valid: false,
                     message: `Total should be ${total}, not ${actualTotal}`}
    } : null;

而不是我的代码中的内容。这样我就可以在组件模板中设置错误消息。

编辑:我做的另一件事是使用价值,而不是actualTotal += +(ctrl.get(refControl).value);. 这是编辑的部分

 arrayValue.forEach(ctrl => {
    actualTotal += +(ctrl[refControl]);
  });

推荐阅读