I'm using the jQuery validation plugin and I want make use of a custom method which takes two the values entered into two different textboxes into account when deciding if the situation is valid.
I know about add method and I've found an example ...
jQuery.validator.addMethod("math", function(value, element, params) {
return this.optional(element) || value == params[0] + params[1];
}, jQuery.format("Please enter the correct value for {0} + {1}"));
... which references two elements but I'm not clear how to write a rule which would make use of a method such as this ?
To make it easier to discuss imagine that I want to make use of this example method and I've got a form that looks like this ..
<form id="TOTALSFORM" name="TOTALSFORM">
<label for="LHSOPERAND">Input 1</label>
<br />
<input type="text" name="LHSOPERAND" id="LHSOPERAND" class="required" />
<br />
<label for="RHSOPERAND">End</label>
<br />
<input type="text" name="RHSOPERAND" id="RHSOPERAND" class="required" />
<label for="TOTAL">End</label>
<br />
<input type="text" name="TOTAL" id="TOTAL" class="required" />
</form>
I've got other rules that I apply like this :
$("#OPTREASON").rules("add", {
required: true,
min: 0,
messages: {
required: "Required input",
min: "Please select a Reason"
}
});
How can I do something similar to apply the example custom method shown so that 'TOTAL' is checked as being the sum of 'LHSOPERAND' and 'RHSOPERAND'.
Try the following:
Create the Rule
jQuery.validator.addMethod("checkTotal",function(value) {
total = parseFloat($('#LHSOPERAND').val()) + parseFloat($('#RHSOPERAND').val());
return total == parseFloat($('#TOTAL').val());
}, "Amounts do not add up!");
jQuery.validator.classRuleSettings.checkTotal = { checkTotal: true };
Input
<input type="text" name="TOTAL" id="TOTAL" class="required checkTotal" />
Init Validation
$(document).ready(function() {
$("#TOTALSFORM").validate();
});
Fiddle here: http://jsfiddle.net/wTMv3/
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