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
?
this.myForm.controls.existObjectsWithThisStudyIdControl.addValidators(Validators.requiredFalse);
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.
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();
}