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

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

问题描述

我想知道如何动态更改字段上的验证.我有对照组,其中有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天全站免登陆