0

I want to add a validator to my FormControl that validates the form if a boolean is false. There is requiredTrue but I need the opposite. Is there a validator for requiredFalse?

  1. this.myForm.controls.existObjectsWithThisStudyIdControl.addValidators(Validators.requiredFalse);

  2. Another option is to rename my variable which is existObjectsWithThisStudyId to noneObjectsExistWithThisStudyId and then use requiredTrue. But it feels like a bad practice for naming.

Mihai Socaciu
  • 155
  • 2
  • 12

1 Answers1

0

You can conditionally add the validator. Ex.

    setFieldValidators()
    {
      if(this.myBooleanValue) { //not required when your boolean is true
        this.myForm.controls.existObjectsWithThisStudyIdControl.setValidators([]);
      }
      else { //required when your boolean is false   
        this.myForm.controls.existObjectsWithThisStudyIdControl.setValidators([Validators.required]);
      }
    this.myForm.controls.existObjectsWithThisStudyIdControl.updateValueAndValidity();
    this.myForm.controls.existObjectsWithThisStudyIdControl.markAsTouched();
    }

You can then set your validator on init, or on any event that that changes your boolean value:

ngOnChanges()
{
  this.setFieldValidators();
}
De Wet van As
  • 904
  • 8
  • 27