如何在启动后更改控件的验证? [英] How to change validation of a control after it has been initiated?

查看:21
本文介绍了如何在启动后更改控件的验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何动态更改字段上的验证.我有控制组,它有 5 个字段.为此,我想在此控制组上使用自定义验证器,以检查是否有任何输入不为空.如果其中任何一个为空,我想将此控制组中的所有字段的验证设置为必需.

I am wondering how can I dynamically change Validation on a field. I have control group, which has 5 fields. For this, I want to use custom validator on this control group, to check if any of the inputs are not empty. If any of those are empty, I want to set validation of all of the fields within this control group to be required.

为此,我需要在验证任何输入为空后,动态更改每个需要的控件的验证.我得到了第一部分 - 但我仍然无法弄清楚如何在启动后更改控件的验证.有什么想法吗?

To do this, I need to dynamically change validation of each control to be required, after I verify if any of the inputs are empty. I got the first part - but I still cant figure out how to change validation of a control after it has been initiated. Any ideas?

我目前正在做的是,我是否像这样在组中放置了一个验证器:

What I am doing at the moment, is I put a validator on the group like this:

this._formBuilder.group({....}, {validator: customValidator})

推荐答案

您可以使用根据值改变行为的自定义验证器

You can use a custom validator that changes behavior depending on a value

class MyComponent {
  constructor(fb:FormBuilder) {
    this.form = fb.group({
      c1: ['', (c) => this.myValidator(c)],
      ...
    });
  }

  someState = true;

  myValidator(c:Control) {
    if(this.someState && control.value ....) {
    }
  }
}

通过这种方式,验证器可以例如访问当前组件的状态.您还可以将验证器移动到另一个类,并将该类的方法引用传递给验证器参数并更新该类的属性以更改验证器的行为.

This way the validator can for example access the status of the current component. You can also move the validator to another class and pass the method reference of that class to the validator parameter and update properties of this class to change the behavior of the validator.

class MyValidator {
  someState = true;

  validate(c:Control) {
    if(this.someState && control.value ....) {
    }
  }
}

class MyComponent {
  myValidator = new MyValidator();

  constructor(fb:FormBuilder) {
    this.form = fb.group({
      c1: ['', this.myValidator.validate.bind(this.myValidator)],
      ...
    });
  }

  onSomeEvent() {
    this.myValidator.someState = !this.myValidator.someState;
    this.form.control.c1.updateValueAndValidity();
  }
}

这篇关于如何在启动后更改控件的验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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