I have requirements like if one field has value make other fields optional/remove required. I have tried like give below example using custom validator but if not use updateValueAndValidity form status not getting updated and it shows invalid and if I am using updateValueAndValidity getting an error RangeError: Maximum call stack size exceeded.
How to solve this.
here is the custom validator code and stackblitz:
EitherMobileOrWorkPhoneRequired(
control: any
): ValidationErrors | null {
const mobile:any = control.get('mobile');
const workPhone:any = control.get('workPhone');
const isNumberEmpty = (formGroup: AbstractControl): boolean => {
const number = (<any>formGroup.get('number')).value;
return number === undefined || number === null || number === '';
};
if (isNumberEmpty(mobile) && isNumberEmpty(workPhone)) {
mobile.get('number').setValidators(Validators.required);
workPhone.get('number').setValidators(Validators.required);
return { required: true };
} else if (isNumberEmpty(mobile)) {
mobile.get('number').clearValidators();
} else if (isNumberEmpty(workPhone)) {
workPhone.get('number').clearValidators();
}
control.updateValueAndValidity();
return null;
}