rrgirish
rrgirish

Reputation: 331

how to use jquery validator to determine value of one field is greater than another field?

I have two fields in a form and I want to add a rule for them saying that id2 cannot have value less than id1

 <input type="text" id="id1">
 <input type="text" id="id2">


id1 : {
                number: true,
                min: 0
            }, 
id2 : {
                number: true,
                min: 0
            } 

Is there a way to set the rule for the jquery validator?

Upvotes: 3

Views: 18635

Answers (2)

callback
callback

Reputation: 4122

You can have the desired behavior with jQuery using the following :

HTML

 <input type="text" id="id1">
 <input type="text" id="id2">
 <input type="submit" id="submit">
 <div class="error" style="display:none">id2 cannot have value less than id1<div>

jQuery

$("#id2").focusout(function(){

    if(parseFloat($("#id1").val()) > parseFloat($("#id2").val()))
    {
        $(".error").css("display","block").css("color","red");
        $("#submit").prop('disabled',true);
    }
    else {
        $(".error").css("display","none");
        $("#submit").prop('disabled',false);        
    }

});

See the jfiddle : http://jsfiddle.net/fyrgazfg/

Upvotes: 3

Denat Hoxha
Denat Hoxha

Reputation: 945

Add a custom method:

$.validator.addMethod("greaterThan",
    function (value, element, param) {
          var $otherElement = $(param);
          return parseInt(value, 10) > parseInt($otherElement.val(), 10);
    });
);

The above code assumes you are using integers. If not, replace parseInt with parseFloat.

Then use it this way in your configuration:

id2: {
    number: true,
    min: 0,
    greaterThan: "#id1"
}

Upvotes: 23

Related Questions