Angular Validator requiredFalse

57 views Asked by At

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.

1

There are 1 answers

0
De Wet van As On BEST ANSWER

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