How to change validation of a control after it has

2019-09-10 12:24发布

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条回答
Viruses.
2楼-- · 2019-09-10 13:23

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();
  }
}
查看更多
登录 后发表回答