Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...