0

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})
uksz
  • 18,239
  • 30
  • 94
  • 161

1 Answers1

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();
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • That's basically what I am doing, however, I would like to know, how I can change the validation of a control at a runtime. Is this possible? – uksz Jun 16 '16 at 07:23
  • Doesn't look like this is supported. You might be able to remove a control and add another one back that has different validators configured. – Günter Zöchbauer Jun 16 '16 at 07:25
  • What do you expect to gain from adding/removing validators compared to the solution in my answer? – Günter Zöchbauer Jun 16 '16 at 07:26
  • It would just be a more convenient way to achieve the same thing, which would result in clearer code I guess. – uksz Jun 16 '16 at 07:28