14

I need help to create custom method to validate sum of multiple text input values.

In form I have variable number of text inputs and when submitting I need to validate that the sum of input values in same group is exactly 100.

example (second group should not validate):

<input type='text' name='g1_number1' class='group1' value='20' />
<input type='text' name='g1_number2' class='group1' value='40' />
<input type='text' name='g1_number3' class='group1' value='40' />

<input type='text' name='g2_number1' class='group2' value='20' />
<input type='text' name='g2_number2' class='group2' value='40' />
<input type='text' name='g2_number3' class='group2' value='10' />
Vertigo
  • 2,714
  • 1
  • 22
  • 24

2 Answers2

18

I got it working this way:

Custom validation rule:

$.validator.addMethod(
    "sum",
    function (value, element, params) {
        var sumOfVals = 0;
        var parent = $(element).parent(".parentDiv");
        $(parent).find("input").each(function () {
            sumOfVals = sumOfVals + parseInt($(this).val(), 10);
        });
        if (sumOfVals == params) return true;
        return false;
    },
    jQuery.format("Sum must be {0}")
);

And using like this:

$(".group1").rules('add', {sum: 100});
$(".group2").rules('add', {sum: 100});
Vertigo
  • 2,714
  • 1
  • 22
  • 24
  • Hi @Vertigo, i am working similar to this, but i am error, when i am adding $(".group1").rules('add', {sum: 100}); – jvk Sep 13 '18 at 17:43
  • on the last if verification of the sumOfVals == params you are missing the brackets for the action in case it is true – FilT Feb 08 '20 at 23:27
6
var sumOfValues=0;
$(".group1").each(function(){
   sumOfValues+=$(this).val();
});
if(sumOfValues==100){

}else{

}

or in plugin form

$.fn.validateValuesSum=function(value){
   var sumOfValues=0;
   this.each(function(){
     sumOfValues+=$(this).val();
   });
   if(sumOfValues==value){
      return true;
   }
   return false;
}
rterrani
  • 526
  • 2
  • 10
  • 5
    `val()` returns a string and might not exactly do what you expect it to. Use `parseFloat($(this).val())` or `Number($(this).val())` to get a numeric value (or a `NaN` that you can check for invalid values). – Klemen Slavič Nov 19 '10 at 13:41
  • 1
    Is there way to implement it in jquery-validation plugin? – Vertigo Nov 20 '10 at 01:24