1

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();
}
4
  • 1
    Can you show us what is your code so far Commented Aug 18, 2017 at 12:09
  • Sure thing, will try post a Plunkr or something soon Commented Aug 18, 2017 at 12:11
  • @Drakkin Plunkr added Commented Aug 18, 2017 at 12:59
  • 1
    Have you tried to do the same as this post ? the function matchingPasswords Commented Aug 18, 2017 at 13:13

1 Answer 1

3

This may not have been the case at the time the question was asked, but now you can use the option emitEvent:false to prevent a new event being emitted.

updateValueAndValidity({ emitEvent: false })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.