Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery-validate - addMethod - how to apply custom rule referencing two text boxes?

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'.

like image 594
shearichard Avatar asked Nov 24 '11 23:11

shearichard


1 Answers

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/

like image 112
dSquared Avatar answered Nov 15 '22 13:11

dSquared