How include/exclude FormControls from validation in large Angular forms












0














In reactive form you can use AbstractFormControl.disable() when you want to exclude particular FormControl/FormGroup from validation. And you can use AbstractFormControl.enable() to do the oposite. But sometimes it is not as easy with large complex forms.



Consider following form:



enter image description here




  • green area is present only if B is checked

  • blue area is present only if E is checked

  • red area is present only if X is checked


The code for the above picture:






   @Component({
selector: 'my-app',
template: `<div [formGroup]="form">
<div style="float: right">
<label for="ctrlX">X</label>
<input type="checkbox" formControlName="ctrlX" />
</div>

<div class="row">
<label for="ctrlA">A</label>
<input type="text" name="ctrlA" formControlName="ctrlA" />
</div>

<div class="row">
<label for="ctrlB">B</label>
<input type="checkbox" name="ctrlB" formControlName="ctrlB" />
</div>

<div *ngIf="form.value.ctrlB === true">
<div [formGroup]="form.get('detailB')">
<div class="row">
<label for="ctrlC">C</label>
<input type="text" name="ctrlC" formControlName="ctrlC" />
</div>

<div class="row" *ngIf="form.value.ctrlX === true">
<label for="ctrlD">D</label>
<input type="text" name="ctrlD" formControlName="ctrlD" />
</div>

<div class="row">
<label for="ctrlE">E</label>
<input type="checkbox" name="ctrlE" formControlName="ctrlE" />
</div>

<div *ngIf="form.value.detailB.ctrlE === true">
<div [formGroup]="form.get('detailB').get('detailE')">
<div class="row">
<label for="ctrlF">F</label>
<input type="text" name="ctrlF" formControlName="ctrlF" />
</div>
</div>
</div>
</div>
</div>
<div class="row">
<label></label>
<button>Submit</button>
</div>
</div>`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
private form = this.formBuilder.group({
ctrlA: ['', Validators.required],
ctrlB: [false],
detailB: this.formBuilder.group({
ctrlC: ['', Validators.required],
ctrlD: ['', Validators.required],
ctrlE: [false],
detailE: this.formBuilder.group({
ctrlF: ['', Validators.required]
})
}),
ctrlX: [true],
});

constructor(private formBuilder: FormBuilder) {}
}





Now the thing is, that you don't want to validate something, that is not visible to the user. But the question is: How to implement this correctly?



Here is what i tried so far.



A: toggling controls one by one demonstrated in this live example

This works as expected, but there are two downsides:




  • code is lengthy, unclear and therefore quite error prone in my opinion

  • this way, some controls are dependent on more than one condition, so you need to combine the conditions as well as merge the valueChanges observables (for example F is dependent not only on E but on B as well)


B: toggling parent formGroups instead of particular formControls demonstrated in live example

Problem is that FormGroup.disable() recursively changes status of each descendant which leaves and form in an inconsistent state compared to UI.



In those live examples you can see what in enabled in the textarea on the bottom of the page.










share|improve this question



























    0














    In reactive form you can use AbstractFormControl.disable() when you want to exclude particular FormControl/FormGroup from validation. And you can use AbstractFormControl.enable() to do the oposite. But sometimes it is not as easy with large complex forms.



    Consider following form:



    enter image description here




    • green area is present only if B is checked

    • blue area is present only if E is checked

    • red area is present only if X is checked


    The code for the above picture:






       @Component({
    selector: 'my-app',
    template: `<div [formGroup]="form">
    <div style="float: right">
    <label for="ctrlX">X</label>
    <input type="checkbox" formControlName="ctrlX" />
    </div>

    <div class="row">
    <label for="ctrlA">A</label>
    <input type="text" name="ctrlA" formControlName="ctrlA" />
    </div>

    <div class="row">
    <label for="ctrlB">B</label>
    <input type="checkbox" name="ctrlB" formControlName="ctrlB" />
    </div>

    <div *ngIf="form.value.ctrlB === true">
    <div [formGroup]="form.get('detailB')">
    <div class="row">
    <label for="ctrlC">C</label>
    <input type="text" name="ctrlC" formControlName="ctrlC" />
    </div>

    <div class="row" *ngIf="form.value.ctrlX === true">
    <label for="ctrlD">D</label>
    <input type="text" name="ctrlD" formControlName="ctrlD" />
    </div>

    <div class="row">
    <label for="ctrlE">E</label>
    <input type="checkbox" name="ctrlE" formControlName="ctrlE" />
    </div>

    <div *ngIf="form.value.detailB.ctrlE === true">
    <div [formGroup]="form.get('detailB').get('detailE')">
    <div class="row">
    <label for="ctrlF">F</label>
    <input type="text" name="ctrlF" formControlName="ctrlF" />
    </div>
    </div>
    </div>
    </div>
    </div>
    <div class="row">
    <label></label>
    <button>Submit</button>
    </div>
    </div>`,
    styleUrls: [ './app.component.css' ]
    })
    export class AppComponent {
    private form = this.formBuilder.group({
    ctrlA: ['', Validators.required],
    ctrlB: [false],
    detailB: this.formBuilder.group({
    ctrlC: ['', Validators.required],
    ctrlD: ['', Validators.required],
    ctrlE: [false],
    detailE: this.formBuilder.group({
    ctrlF: ['', Validators.required]
    })
    }),
    ctrlX: [true],
    });

    constructor(private formBuilder: FormBuilder) {}
    }





    Now the thing is, that you don't want to validate something, that is not visible to the user. But the question is: How to implement this correctly?



    Here is what i tried so far.



    A: toggling controls one by one demonstrated in this live example

    This works as expected, but there are two downsides:




    • code is lengthy, unclear and therefore quite error prone in my opinion

    • this way, some controls are dependent on more than one condition, so you need to combine the conditions as well as merge the valueChanges observables (for example F is dependent not only on E but on B as well)


    B: toggling parent formGroups instead of particular formControls demonstrated in live example

    Problem is that FormGroup.disable() recursively changes status of each descendant which leaves and form in an inconsistent state compared to UI.



    In those live examples you can see what in enabled in the textarea on the bottom of the page.










    share|improve this question

























      0












      0








      0







      In reactive form you can use AbstractFormControl.disable() when you want to exclude particular FormControl/FormGroup from validation. And you can use AbstractFormControl.enable() to do the oposite. But sometimes it is not as easy with large complex forms.



      Consider following form:



      enter image description here




      • green area is present only if B is checked

      • blue area is present only if E is checked

      • red area is present only if X is checked


      The code for the above picture:






         @Component({
      selector: 'my-app',
      template: `<div [formGroup]="form">
      <div style="float: right">
      <label for="ctrlX">X</label>
      <input type="checkbox" formControlName="ctrlX" />
      </div>

      <div class="row">
      <label for="ctrlA">A</label>
      <input type="text" name="ctrlA" formControlName="ctrlA" />
      </div>

      <div class="row">
      <label for="ctrlB">B</label>
      <input type="checkbox" name="ctrlB" formControlName="ctrlB" />
      </div>

      <div *ngIf="form.value.ctrlB === true">
      <div [formGroup]="form.get('detailB')">
      <div class="row">
      <label for="ctrlC">C</label>
      <input type="text" name="ctrlC" formControlName="ctrlC" />
      </div>

      <div class="row" *ngIf="form.value.ctrlX === true">
      <label for="ctrlD">D</label>
      <input type="text" name="ctrlD" formControlName="ctrlD" />
      </div>

      <div class="row">
      <label for="ctrlE">E</label>
      <input type="checkbox" name="ctrlE" formControlName="ctrlE" />
      </div>

      <div *ngIf="form.value.detailB.ctrlE === true">
      <div [formGroup]="form.get('detailB').get('detailE')">
      <div class="row">
      <label for="ctrlF">F</label>
      <input type="text" name="ctrlF" formControlName="ctrlF" />
      </div>
      </div>
      </div>
      </div>
      </div>
      <div class="row">
      <label></label>
      <button>Submit</button>
      </div>
      </div>`,
      styleUrls: [ './app.component.css' ]
      })
      export class AppComponent {
      private form = this.formBuilder.group({
      ctrlA: ['', Validators.required],
      ctrlB: [false],
      detailB: this.formBuilder.group({
      ctrlC: ['', Validators.required],
      ctrlD: ['', Validators.required],
      ctrlE: [false],
      detailE: this.formBuilder.group({
      ctrlF: ['', Validators.required]
      })
      }),
      ctrlX: [true],
      });

      constructor(private formBuilder: FormBuilder) {}
      }





      Now the thing is, that you don't want to validate something, that is not visible to the user. But the question is: How to implement this correctly?



      Here is what i tried so far.



      A: toggling controls one by one demonstrated in this live example

      This works as expected, but there are two downsides:




      • code is lengthy, unclear and therefore quite error prone in my opinion

      • this way, some controls are dependent on more than one condition, so you need to combine the conditions as well as merge the valueChanges observables (for example F is dependent not only on E but on B as well)


      B: toggling parent formGroups instead of particular formControls demonstrated in live example

      Problem is that FormGroup.disable() recursively changes status of each descendant which leaves and form in an inconsistent state compared to UI.



      In those live examples you can see what in enabled in the textarea on the bottom of the page.










      share|improve this question













      In reactive form you can use AbstractFormControl.disable() when you want to exclude particular FormControl/FormGroup from validation. And you can use AbstractFormControl.enable() to do the oposite. But sometimes it is not as easy with large complex forms.



      Consider following form:



      enter image description here




      • green area is present only if B is checked

      • blue area is present only if E is checked

      • red area is present only if X is checked


      The code for the above picture:






         @Component({
      selector: 'my-app',
      template: `<div [formGroup]="form">
      <div style="float: right">
      <label for="ctrlX">X</label>
      <input type="checkbox" formControlName="ctrlX" />
      </div>

      <div class="row">
      <label for="ctrlA">A</label>
      <input type="text" name="ctrlA" formControlName="ctrlA" />
      </div>

      <div class="row">
      <label for="ctrlB">B</label>
      <input type="checkbox" name="ctrlB" formControlName="ctrlB" />
      </div>

      <div *ngIf="form.value.ctrlB === true">
      <div [formGroup]="form.get('detailB')">
      <div class="row">
      <label for="ctrlC">C</label>
      <input type="text" name="ctrlC" formControlName="ctrlC" />
      </div>

      <div class="row" *ngIf="form.value.ctrlX === true">
      <label for="ctrlD">D</label>
      <input type="text" name="ctrlD" formControlName="ctrlD" />
      </div>

      <div class="row">
      <label for="ctrlE">E</label>
      <input type="checkbox" name="ctrlE" formControlName="ctrlE" />
      </div>

      <div *ngIf="form.value.detailB.ctrlE === true">
      <div [formGroup]="form.get('detailB').get('detailE')">
      <div class="row">
      <label for="ctrlF">F</label>
      <input type="text" name="ctrlF" formControlName="ctrlF" />
      </div>
      </div>
      </div>
      </div>
      </div>
      <div class="row">
      <label></label>
      <button>Submit</button>
      </div>
      </div>`,
      styleUrls: [ './app.component.css' ]
      })
      export class AppComponent {
      private form = this.formBuilder.group({
      ctrlA: ['', Validators.required],
      ctrlB: [false],
      detailB: this.formBuilder.group({
      ctrlC: ['', Validators.required],
      ctrlD: ['', Validators.required],
      ctrlE: [false],
      detailE: this.formBuilder.group({
      ctrlF: ['', Validators.required]
      })
      }),
      ctrlX: [true],
      });

      constructor(private formBuilder: FormBuilder) {}
      }





      Now the thing is, that you don't want to validate something, that is not visible to the user. But the question is: How to implement this correctly?



      Here is what i tried so far.



      A: toggling controls one by one demonstrated in this live example

      This works as expected, but there are two downsides:




      • code is lengthy, unclear and therefore quite error prone in my opinion

      • this way, some controls are dependent on more than one condition, so you need to combine the conditions as well as merge the valueChanges observables (for example F is dependent not only on E but on B as well)


      B: toggling parent formGroups instead of particular formControls demonstrated in live example

      Problem is that FormGroup.disable() recursively changes status of each descendant which leaves and form in an inconsistent state compared to UI.



      In those live examples you can see what in enabled in the textarea on the bottom of the page.






         @Component({
      selector: 'my-app',
      template: `<div [formGroup]="form">
      <div style="float: right">
      <label for="ctrlX">X</label>
      <input type="checkbox" formControlName="ctrlX" />
      </div>

      <div class="row">
      <label for="ctrlA">A</label>
      <input type="text" name="ctrlA" formControlName="ctrlA" />
      </div>

      <div class="row">
      <label for="ctrlB">B</label>
      <input type="checkbox" name="ctrlB" formControlName="ctrlB" />
      </div>

      <div *ngIf="form.value.ctrlB === true">
      <div [formGroup]="form.get('detailB')">
      <div class="row">
      <label for="ctrlC">C</label>
      <input type="text" name="ctrlC" formControlName="ctrlC" />
      </div>

      <div class="row" *ngIf="form.value.ctrlX === true">
      <label for="ctrlD">D</label>
      <input type="text" name="ctrlD" formControlName="ctrlD" />
      </div>

      <div class="row">
      <label for="ctrlE">E</label>
      <input type="checkbox" name="ctrlE" formControlName="ctrlE" />
      </div>

      <div *ngIf="form.value.detailB.ctrlE === true">
      <div [formGroup]="form.get('detailB').get('detailE')">
      <div class="row">
      <label for="ctrlF">F</label>
      <input type="text" name="ctrlF" formControlName="ctrlF" />
      </div>
      </div>
      </div>
      </div>
      </div>
      <div class="row">
      <label></label>
      <button>Submit</button>
      </div>
      </div>`,
      styleUrls: [ './app.component.css' ]
      })
      export class AppComponent {
      private form = this.formBuilder.group({
      ctrlA: ['', Validators.required],
      ctrlB: [false],
      detailB: this.formBuilder.group({
      ctrlC: ['', Validators.required],
      ctrlD: ['', Validators.required],
      ctrlE: [false],
      detailE: this.formBuilder.group({
      ctrlF: ['', Validators.required]
      })
      }),
      ctrlX: [true],
      });

      constructor(private formBuilder: FormBuilder) {}
      }





         @Component({
      selector: 'my-app',
      template: `<div [formGroup]="form">
      <div style="float: right">
      <label for="ctrlX">X</label>
      <input type="checkbox" formControlName="ctrlX" />
      </div>

      <div class="row">
      <label for="ctrlA">A</label>
      <input type="text" name="ctrlA" formControlName="ctrlA" />
      </div>

      <div class="row">
      <label for="ctrlB">B</label>
      <input type="checkbox" name="ctrlB" formControlName="ctrlB" />
      </div>

      <div *ngIf="form.value.ctrlB === true">
      <div [formGroup]="form.get('detailB')">
      <div class="row">
      <label for="ctrlC">C</label>
      <input type="text" name="ctrlC" formControlName="ctrlC" />
      </div>

      <div class="row" *ngIf="form.value.ctrlX === true">
      <label for="ctrlD">D</label>
      <input type="text" name="ctrlD" formControlName="ctrlD" />
      </div>

      <div class="row">
      <label for="ctrlE">E</label>
      <input type="checkbox" name="ctrlE" formControlName="ctrlE" />
      </div>

      <div *ngIf="form.value.detailB.ctrlE === true">
      <div [formGroup]="form.get('detailB').get('detailE')">
      <div class="row">
      <label for="ctrlF">F</label>
      <input type="text" name="ctrlF" formControlName="ctrlF" />
      </div>
      </div>
      </div>
      </div>
      </div>
      <div class="row">
      <label></label>
      <button>Submit</button>
      </div>
      </div>`,
      styleUrls: [ './app.component.css' ]
      })
      export class AppComponent {
      private form = this.formBuilder.group({
      ctrlA: ['', Validators.required],
      ctrlB: [false],
      detailB: this.formBuilder.group({
      ctrlC: ['', Validators.required],
      ctrlD: ['', Validators.required],
      ctrlE: [false],
      detailE: this.formBuilder.group({
      ctrlF: ['', Validators.required]
      })
      }),
      ctrlX: [true],
      });

      constructor(private formBuilder: FormBuilder) {}
      }






      angular angular-reactive-forms






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 16:53









      adosanadosan

      12617




      12617
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You can use this.formGroup.setValidators(ValidatorFunction). The Validator function can accept formGroup as a parameter. You can check values and return the error object or null. You dont need to depend on any observable here (removes your cons in condition A, the code may be lengthy depending upon conditions). As for B, the form will always be in a consistent state since you are not manually enabling/disabling the controls.






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53416992%2fhow-include-exclude-formcontrols-from-validation-in-large-angular-forms%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You can use this.formGroup.setValidators(ValidatorFunction). The Validator function can accept formGroup as a parameter. You can check values and return the error object or null. You dont need to depend on any observable here (removes your cons in condition A, the code may be lengthy depending upon conditions). As for B, the form will always be in a consistent state since you are not manually enabling/disabling the controls.






            share|improve this answer


























              1














              You can use this.formGroup.setValidators(ValidatorFunction). The Validator function can accept formGroup as a parameter. You can check values and return the error object or null. You dont need to depend on any observable here (removes your cons in condition A, the code may be lengthy depending upon conditions). As for B, the form will always be in a consistent state since you are not manually enabling/disabling the controls.






              share|improve this answer
























                1












                1








                1






                You can use this.formGroup.setValidators(ValidatorFunction). The Validator function can accept formGroup as a parameter. You can check values and return the error object or null. You dont need to depend on any observable here (removes your cons in condition A, the code may be lengthy depending upon conditions). As for B, the form will always be in a consistent state since you are not manually enabling/disabling the controls.






                share|improve this answer












                You can use this.formGroup.setValidators(ValidatorFunction). The Validator function can accept formGroup as a parameter. You can check values and return the error object or null. You dont need to depend on any observable here (removes your cons in condition A, the code may be lengthy depending upon conditions). As for B, the form will always be in a consistent state since you are not manually enabling/disabling the controls.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 21 '18 at 17:21









                Sachin GuptaSachin Gupta

                653311




                653311






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53416992%2fhow-include-exclude-formcontrols-from-validation-in-large-angular-forms%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Wiesbaden

                    Marschland

                    Dieringhausen