How to change validation of a control after it has been initiated?

我与影子孤独终老i 提交于 2019-12-12 01:29:29

问题


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})

回答1:


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();
  }
}


来源:https://stackoverflow.com/questions/37852315/how-to-change-validation-of-a-control-after-it-has-been-initiated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!