Validate sum of reactive form elements





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I have a reactive form that is basically this.



ngOnInit() {

this.myForm = this.fb.group({
sections: this.fb.array()
});
}

addSection(){
let section = <FormArray>this.myForm.controls.sections;
section.push(this.fb.group({
name: '',
items: this.fb.array(),
percentage: '',
}));
}


addSection() is a function that adds an element to my sections FormArray when i click something that's on my template



I sum up all percentages from every section inside the sections formArray and validate that it isn't bigger than 1 (I assume user is typing floating points in those specific inputs). Finally i want to disable the submit button at the end of the form if the sum if bigger than 1.



I tried the answer from this question but didn't work cause https://stackoverflow.com/a/48706808/8579973 cause it was meant for a group of object thats all the same. I need it to validate just the "percentage" element from every group that is made.



I also tried to store the sum in local storage, but I don't want any extra button that triggers that procedure.



Thanks for your answers,
Regards










share|improve this question





























    0















    I have a reactive form that is basically this.



    ngOnInit() {

    this.myForm = this.fb.group({
    sections: this.fb.array()
    });
    }

    addSection(){
    let section = <FormArray>this.myForm.controls.sections;
    section.push(this.fb.group({
    name: '',
    items: this.fb.array(),
    percentage: '',
    }));
    }


    addSection() is a function that adds an element to my sections FormArray when i click something that's on my template



    I sum up all percentages from every section inside the sections formArray and validate that it isn't bigger than 1 (I assume user is typing floating points in those specific inputs). Finally i want to disable the submit button at the end of the form if the sum if bigger than 1.



    I tried the answer from this question but didn't work cause https://stackoverflow.com/a/48706808/8579973 cause it was meant for a group of object thats all the same. I need it to validate just the "percentage" element from every group that is made.



    I also tried to store the sum in local storage, but I don't want any extra button that triggers that procedure.



    Thanks for your answers,
    Regards










    share|improve this question

























      0












      0








      0








      I have a reactive form that is basically this.



      ngOnInit() {

      this.myForm = this.fb.group({
      sections: this.fb.array()
      });
      }

      addSection(){
      let section = <FormArray>this.myForm.controls.sections;
      section.push(this.fb.group({
      name: '',
      items: this.fb.array(),
      percentage: '',
      }));
      }


      addSection() is a function that adds an element to my sections FormArray when i click something that's on my template



      I sum up all percentages from every section inside the sections formArray and validate that it isn't bigger than 1 (I assume user is typing floating points in those specific inputs). Finally i want to disable the submit button at the end of the form if the sum if bigger than 1.



      I tried the answer from this question but didn't work cause https://stackoverflow.com/a/48706808/8579973 cause it was meant for a group of object thats all the same. I need it to validate just the "percentage" element from every group that is made.



      I also tried to store the sum in local storage, but I don't want any extra button that triggers that procedure.



      Thanks for your answers,
      Regards










      share|improve this question














      I have a reactive form that is basically this.



      ngOnInit() {

      this.myForm = this.fb.group({
      sections: this.fb.array()
      });
      }

      addSection(){
      let section = <FormArray>this.myForm.controls.sections;
      section.push(this.fb.group({
      name: '',
      items: this.fb.array(),
      percentage: '',
      }));
      }


      addSection() is a function that adds an element to my sections FormArray when i click something that's on my template



      I sum up all percentages from every section inside the sections formArray and validate that it isn't bigger than 1 (I assume user is typing floating points in those specific inputs). Finally i want to disable the submit button at the end of the form if the sum if bigger than 1.



      I tried the answer from this question but didn't work cause https://stackoverflow.com/a/48706808/8579973 cause it was meant for a group of object thats all the same. I need it to validate just the "percentage" element from every group that is made.



      I also tried to store the sum in local storage, but I don't want any extra button that triggers that procedure.



      Thanks for your answers,
      Regards







      javascript angular typescript angular6






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 23:05









      KaiserCLKaiserCL

      13118




      13118
























          1 Answer
          1






          active

          oldest

          votes


















          1














          Like this? Stackblitz: https://stackblitz.com/edit/angular-vdgdv2



          import { Component} from '@angular/core';
          import {FormBuilder, FormControl, FormArray, FormGroup, FormGroupDirective, NgForm, ValidatorFn, Validators} from '@angular/forms';


          @Component({
          selector: 'my-app',
          templateUrl: './app.component.html',
          styleUrls: [ './app.component.css' ]
          })
          export class AppComponent{
          myForm: FormGroup;
          constructor(private fb: FormBuilder){
          this.myForm = this.fb.group({
          sections: this.fb.array(, CustomValidator.checkPercentageSum)
          });
          this.addSection();
          }

          addSection(){
          let section = this.myForm.get('sections') as FormArray;
          section.push(this.fb.group({
          percentage: 0.2,
          }));
          section.push(this.fb.group({
          percentage: 0.3,
          }));
          section.push(this.fb.group({
          percentage: 1,
          }));

          console.log(this.myForm.valid , this.myForm.get('sections').errors);
          // Output: false {Invalid: true}
          }

          }

          //Custom Validator
          export class CustomValidator {
          static checkPercentageSum(sections: FormArray): ValidationResult {
          if (sections) {
          let sumOfPercentages: number = 0;
          sections['controls'].forEach((sectionItem: FormGroup) => {
          sumOfPercentages = sectionItem['controls'].percentage.value + sumOfPercentages;
          });

          if (sumOfPercentages > 1) {
          return {"Invalid": true};
          }
          }
          return null;
          }
          }

          export interface ValidationResult {
          [key: string]: boolean;
          }





          share|improve this answer
























          • Thanks for your answer, but that is not what i need. Percentage is a % that the user decides. E.g., if the user creates 4 sections he could assign 0.25 (25%), to each, the result would be 100%. I just need to validate that the sum of control percentage of every sections that the user creates is not > 1

            – KaiserCL
            Nov 23 '18 at 11:22






          • 1





            I think that is what my answer shows - a custom validator that will validate the sum of all percentage fields. The addSection() part you have to figure out. I just did multiple section.push for demonstration purposes.

            – zer0
            Nov 23 '18 at 15:17











          • Genius, this solves my problem ... At first I didn't get those section.push. Thank you very much!

            – KaiserCL
            Nov 23 '18 at 17:07








          • 1





            Glad I could help :)

            – zer0
            Nov 23 '18 at 17:40












          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%2f53438912%2fvalidate-sum-of-reactive-form-elements%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














          Like this? Stackblitz: https://stackblitz.com/edit/angular-vdgdv2



          import { Component} from '@angular/core';
          import {FormBuilder, FormControl, FormArray, FormGroup, FormGroupDirective, NgForm, ValidatorFn, Validators} from '@angular/forms';


          @Component({
          selector: 'my-app',
          templateUrl: './app.component.html',
          styleUrls: [ './app.component.css' ]
          })
          export class AppComponent{
          myForm: FormGroup;
          constructor(private fb: FormBuilder){
          this.myForm = this.fb.group({
          sections: this.fb.array(, CustomValidator.checkPercentageSum)
          });
          this.addSection();
          }

          addSection(){
          let section = this.myForm.get('sections') as FormArray;
          section.push(this.fb.group({
          percentage: 0.2,
          }));
          section.push(this.fb.group({
          percentage: 0.3,
          }));
          section.push(this.fb.group({
          percentage: 1,
          }));

          console.log(this.myForm.valid , this.myForm.get('sections').errors);
          // Output: false {Invalid: true}
          }

          }

          //Custom Validator
          export class CustomValidator {
          static checkPercentageSum(sections: FormArray): ValidationResult {
          if (sections) {
          let sumOfPercentages: number = 0;
          sections['controls'].forEach((sectionItem: FormGroup) => {
          sumOfPercentages = sectionItem['controls'].percentage.value + sumOfPercentages;
          });

          if (sumOfPercentages > 1) {
          return {"Invalid": true};
          }
          }
          return null;
          }
          }

          export interface ValidationResult {
          [key: string]: boolean;
          }





          share|improve this answer
























          • Thanks for your answer, but that is not what i need. Percentage is a % that the user decides. E.g., if the user creates 4 sections he could assign 0.25 (25%), to each, the result would be 100%. I just need to validate that the sum of control percentage of every sections that the user creates is not > 1

            – KaiserCL
            Nov 23 '18 at 11:22






          • 1





            I think that is what my answer shows - a custom validator that will validate the sum of all percentage fields. The addSection() part you have to figure out. I just did multiple section.push for demonstration purposes.

            – zer0
            Nov 23 '18 at 15:17











          • Genius, this solves my problem ... At first I didn't get those section.push. Thank you very much!

            – KaiserCL
            Nov 23 '18 at 17:07








          • 1





            Glad I could help :)

            – zer0
            Nov 23 '18 at 17:40
















          1














          Like this? Stackblitz: https://stackblitz.com/edit/angular-vdgdv2



          import { Component} from '@angular/core';
          import {FormBuilder, FormControl, FormArray, FormGroup, FormGroupDirective, NgForm, ValidatorFn, Validators} from '@angular/forms';


          @Component({
          selector: 'my-app',
          templateUrl: './app.component.html',
          styleUrls: [ './app.component.css' ]
          })
          export class AppComponent{
          myForm: FormGroup;
          constructor(private fb: FormBuilder){
          this.myForm = this.fb.group({
          sections: this.fb.array(, CustomValidator.checkPercentageSum)
          });
          this.addSection();
          }

          addSection(){
          let section = this.myForm.get('sections') as FormArray;
          section.push(this.fb.group({
          percentage: 0.2,
          }));
          section.push(this.fb.group({
          percentage: 0.3,
          }));
          section.push(this.fb.group({
          percentage: 1,
          }));

          console.log(this.myForm.valid , this.myForm.get('sections').errors);
          // Output: false {Invalid: true}
          }

          }

          //Custom Validator
          export class CustomValidator {
          static checkPercentageSum(sections: FormArray): ValidationResult {
          if (sections) {
          let sumOfPercentages: number = 0;
          sections['controls'].forEach((sectionItem: FormGroup) => {
          sumOfPercentages = sectionItem['controls'].percentage.value + sumOfPercentages;
          });

          if (sumOfPercentages > 1) {
          return {"Invalid": true};
          }
          }
          return null;
          }
          }

          export interface ValidationResult {
          [key: string]: boolean;
          }





          share|improve this answer
























          • Thanks for your answer, but that is not what i need. Percentage is a % that the user decides. E.g., if the user creates 4 sections he could assign 0.25 (25%), to each, the result would be 100%. I just need to validate that the sum of control percentage of every sections that the user creates is not > 1

            – KaiserCL
            Nov 23 '18 at 11:22






          • 1





            I think that is what my answer shows - a custom validator that will validate the sum of all percentage fields. The addSection() part you have to figure out. I just did multiple section.push for demonstration purposes.

            – zer0
            Nov 23 '18 at 15:17











          • Genius, this solves my problem ... At first I didn't get those section.push. Thank you very much!

            – KaiserCL
            Nov 23 '18 at 17:07








          • 1





            Glad I could help :)

            – zer0
            Nov 23 '18 at 17:40














          1












          1








          1







          Like this? Stackblitz: https://stackblitz.com/edit/angular-vdgdv2



          import { Component} from '@angular/core';
          import {FormBuilder, FormControl, FormArray, FormGroup, FormGroupDirective, NgForm, ValidatorFn, Validators} from '@angular/forms';


          @Component({
          selector: 'my-app',
          templateUrl: './app.component.html',
          styleUrls: [ './app.component.css' ]
          })
          export class AppComponent{
          myForm: FormGroup;
          constructor(private fb: FormBuilder){
          this.myForm = this.fb.group({
          sections: this.fb.array(, CustomValidator.checkPercentageSum)
          });
          this.addSection();
          }

          addSection(){
          let section = this.myForm.get('sections') as FormArray;
          section.push(this.fb.group({
          percentage: 0.2,
          }));
          section.push(this.fb.group({
          percentage: 0.3,
          }));
          section.push(this.fb.group({
          percentage: 1,
          }));

          console.log(this.myForm.valid , this.myForm.get('sections').errors);
          // Output: false {Invalid: true}
          }

          }

          //Custom Validator
          export class CustomValidator {
          static checkPercentageSum(sections: FormArray): ValidationResult {
          if (sections) {
          let sumOfPercentages: number = 0;
          sections['controls'].forEach((sectionItem: FormGroup) => {
          sumOfPercentages = sectionItem['controls'].percentage.value + sumOfPercentages;
          });

          if (sumOfPercentages > 1) {
          return {"Invalid": true};
          }
          }
          return null;
          }
          }

          export interface ValidationResult {
          [key: string]: boolean;
          }





          share|improve this answer













          Like this? Stackblitz: https://stackblitz.com/edit/angular-vdgdv2



          import { Component} from '@angular/core';
          import {FormBuilder, FormControl, FormArray, FormGroup, FormGroupDirective, NgForm, ValidatorFn, Validators} from '@angular/forms';


          @Component({
          selector: 'my-app',
          templateUrl: './app.component.html',
          styleUrls: [ './app.component.css' ]
          })
          export class AppComponent{
          myForm: FormGroup;
          constructor(private fb: FormBuilder){
          this.myForm = this.fb.group({
          sections: this.fb.array(, CustomValidator.checkPercentageSum)
          });
          this.addSection();
          }

          addSection(){
          let section = this.myForm.get('sections') as FormArray;
          section.push(this.fb.group({
          percentage: 0.2,
          }));
          section.push(this.fb.group({
          percentage: 0.3,
          }));
          section.push(this.fb.group({
          percentage: 1,
          }));

          console.log(this.myForm.valid , this.myForm.get('sections').errors);
          // Output: false {Invalid: true}
          }

          }

          //Custom Validator
          export class CustomValidator {
          static checkPercentageSum(sections: FormArray): ValidationResult {
          if (sections) {
          let sumOfPercentages: number = 0;
          sections['controls'].forEach((sectionItem: FormGroup) => {
          sumOfPercentages = sectionItem['controls'].percentage.value + sumOfPercentages;
          });

          if (sumOfPercentages > 1) {
          return {"Invalid": true};
          }
          }
          return null;
          }
          }

          export interface ValidationResult {
          [key: string]: boolean;
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 3:40









          zer0zer0

          1,18421229




          1,18421229













          • Thanks for your answer, but that is not what i need. Percentage is a % that the user decides. E.g., if the user creates 4 sections he could assign 0.25 (25%), to each, the result would be 100%. I just need to validate that the sum of control percentage of every sections that the user creates is not > 1

            – KaiserCL
            Nov 23 '18 at 11:22






          • 1





            I think that is what my answer shows - a custom validator that will validate the sum of all percentage fields. The addSection() part you have to figure out. I just did multiple section.push for demonstration purposes.

            – zer0
            Nov 23 '18 at 15:17











          • Genius, this solves my problem ... At first I didn't get those section.push. Thank you very much!

            – KaiserCL
            Nov 23 '18 at 17:07








          • 1





            Glad I could help :)

            – zer0
            Nov 23 '18 at 17:40



















          • Thanks for your answer, but that is not what i need. Percentage is a % that the user decides. E.g., if the user creates 4 sections he could assign 0.25 (25%), to each, the result would be 100%. I just need to validate that the sum of control percentage of every sections that the user creates is not > 1

            – KaiserCL
            Nov 23 '18 at 11:22






          • 1





            I think that is what my answer shows - a custom validator that will validate the sum of all percentage fields. The addSection() part you have to figure out. I just did multiple section.push for demonstration purposes.

            – zer0
            Nov 23 '18 at 15:17











          • Genius, this solves my problem ... At first I didn't get those section.push. Thank you very much!

            – KaiserCL
            Nov 23 '18 at 17:07








          • 1





            Glad I could help :)

            – zer0
            Nov 23 '18 at 17:40

















          Thanks for your answer, but that is not what i need. Percentage is a % that the user decides. E.g., if the user creates 4 sections he could assign 0.25 (25%), to each, the result would be 100%. I just need to validate that the sum of control percentage of every sections that the user creates is not > 1

          – KaiserCL
          Nov 23 '18 at 11:22





          Thanks for your answer, but that is not what i need. Percentage is a % that the user decides. E.g., if the user creates 4 sections he could assign 0.25 (25%), to each, the result would be 100%. I just need to validate that the sum of control percentage of every sections that the user creates is not > 1

          – KaiserCL
          Nov 23 '18 at 11:22




          1




          1





          I think that is what my answer shows - a custom validator that will validate the sum of all percentage fields. The addSection() part you have to figure out. I just did multiple section.push for demonstration purposes.

          – zer0
          Nov 23 '18 at 15:17





          I think that is what my answer shows - a custom validator that will validate the sum of all percentage fields. The addSection() part you have to figure out. I just did multiple section.push for demonstration purposes.

          – zer0
          Nov 23 '18 at 15:17













          Genius, this solves my problem ... At first I didn't get those section.push. Thank you very much!

          – KaiserCL
          Nov 23 '18 at 17:07







          Genius, this solves my problem ... At first I didn't get those section.push. Thank you very much!

          – KaiserCL
          Nov 23 '18 at 17:07






          1




          1





          Glad I could help :)

          – zer0
          Nov 23 '18 at 17:40





          Glad I could help :)

          – zer0
          Nov 23 '18 at 17:40




















          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%2f53438912%2fvalidate-sum-of-reactive-form-elements%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

          How to change which sound is reproduced for terminal bell?

          Can I use Tabulator js library in my java Spring + Thymeleaf project?

          Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents