Background
I have a form with multiple fields that affect the validation of one another.
As a simple example, let's take a simple form with a CellNo (Cellphone number) and HomeNo (a Home contact number).
Both have validation applied to them for detecting the validity of the numbers themselves, however: If a CellNo is entered - the HomeNo field isn't required, and visa versa.
I implement a subscription to the valueChanges of each field which then updates the Validators of each field based on the FormControl values of each, and then calls the updateValueAndValidity() function.
By calling this function however, it triggers the valueChanges subscription of each field, causing an infinite loop.
Question
What would be the best way to go about achieving this with a FormBuilder?
Edit 1: Replicated my issue in a Plunkr.
Open your console/devtools to see the looping output. The function that gets called repeatedly is:
updatePhoneValidations() {
console.log('Updating validations');
let cellValidators = [Validators.pattern(this.PHONE_REGEX), Validators.maxLength(25)];
if (this.inputForm.controls.HomeNo.value.length === 0) {
this.inputForm.controls.CellNo.setValidators([...cellValidators, Validators.required]);
} else {
console.log('Removing CellNo');
this.inputForm.controls.CellNo.setValidators([...cellValidators]);
}
this.inputForm.controls.CellNo.updateValueAndValidity();
let homeNoValidators = [Validators.pattern(this.PHONE_REGEX), Validators.maxLength(25)];
if (this.inputForm.controls.CellNo.value.length === 0 ) {
this.inputForm.controls.HomeNo.setValidators([...homeNoValidators, Validators.required]);
} else {
console.log('Removing HomeNo', this.inputForm.controls.HomeNo);
this.inputForm.controls.HomeNo.setValidators([...homeNoValidators]);
}
this.inputForm.controls.HomeNo.updateValueAndValidity();
}