Angular 5:通过汇总值来验证多个输入字段 [英] Angular 5: Validate multiple input fields by sum up values

查看:25
本文介绍了Angular 5:通过汇总值来验证多个输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过总结它们的值来验证多个数字输入字段,并为 Angular 创建一个自定义验证器.

I would like to validate multiple number input fields by sum up their values and create a custom Validator for Angular.

每个输入看起来像这样:

Every Input looks like this:

<input type="number" min="0" max="10">

有多个数字输入,每个人都可以有一个 0 到 10 之间的值,但所有字段的总和必须小于或等于 10.

There are multiple number inputs and everyone can have a value between 0 and 10, but the sum of all fields must be less or equal 10.

我有一个函数,如果所有输入字段的总和小于或等于 10,则返回 true.但是我如何使用自定义 Angular Validator 实现这一点?以便立即显示错误消息.

I have a function that returns true if the sum of all input fields is less or equal 10. But how I achieve this with a custom Angular Validator? So that the error message appear instantly.

推荐答案

就像提到的组本身的设置验证一样,例如:

Like mentioned set validation on the group itself, so do for example:

this.myForm = fb.group({
  field1: [null],
  field2: [null]
  // more fields 
}, {validator: this.myValidator})

然后在您的验证器中迭代您组中的表单控件,根据有效与否总结并返回错误或null:

Then in your validator iterate the formcontrols in your group, sum up and return error or null based on valid or not:

myValidator(group: FormGroup) {
  let sum = 0;
  for(let a in group.controls) {
    sum += group.get([a]).value;
  }
  return sum > 10 ? { notValid: true} : null
}

并且在模板中您可以使用以下方式显示错误:

and in template you can display error with:

*ngIf="myForm.hasError('notValid')"

这篇关于Angular 5:通过汇总值来验证多个输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆