Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 878
rrgirish Avatar asked Dec 09 '25 00:12

rrgirish


2 Answers

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"
}
like image 90
Denat Hoxha Avatar answered Dec 10 '25 12:12

Denat Hoxha


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/

like image 27
callback Avatar answered Dec 10 '25 13:12

callback



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!