Custom validator with condition only detect changes once

I have a FormGroup look like this:

this.complaint = new FormGroup({
      date: new FormControl(null, Validators.required),
      isRangeDate: new FormControl(false, Validators.required),
      untilDate: new FormControl(null, rangeDateValidator()),
    });

and I have this custom validator rangeDateValidator

function rangeDateValidator(): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    console.log(control?.parent?.get('isRangeDate')?.value)
    return control?.parent?.get('isRangeDate')?.value ? {required: true} : null;
  }
}

that basically check if user chose to input range date and if so - it's change the untilDate control to be required. this thing is working only in the first time - isRangeDate by default is false so it's no required validation added to the control, and when it change to true it's add the required to the control, but only once - when I change it back to isRangeDate: false, the required validation still attach to it and I can see in the console that the validator function didn't call, even the FormGroup is changed.

any ideas?


Solution 1:

It does not call you're custom validator because you are changing the isRangeDate form and not the untilDate form, you only assign the custom validator to the untilDate form. Maybe you can call a function after changing the isRangeDate form with: myForm.markAllAsTouched() or myForm.valid(). I think this should revalidate the form and call the custom validator.