开发者

jquery validate: sum of multiple input values

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_numbe开发者_开发百科r3' 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' />


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});


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜