角度5:通过求和值验证多个输入字段 [英] Angular 5: Validate multiple input fields by sum up values

查看:61
本文介绍了角度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})

然后在验证器中迭代组中的formcontrol,总结并根据有效与否返回错误或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')"

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

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