Angular 2 FormBuilder w/ Custom/Dynamic Validation loop -


background

i have form multiple fields affect validation of 1 another.

as simple example, let's take simple form cellno (cellphone number) , homeno (a home contact number).

both have validation applied them detecting validity of numbers themselves, however: if cellno entered - homeno field isn't required, and visa versa.

i implement subscription valuechanges of each field updates validators of each field based on formcontrol values of each, , calls updatevalueandvalidity() function.

by calling function however, triggers valuechanges subscription of each field, causing infinite loop.

question

what best way go achieving formbuilder?

edit 1: replicated issue in plunkr.

open console/devtools see looping output. function 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(); } 


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -