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' />
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With