jQuery validate less than

后端 未结 5 1791
盖世英雄少女心
盖世英雄少女心 2020-12-15 12:05

I am trying to write a Less than validator for jQuery.

I want to compare one text box against another, so if I have:



        
5条回答
  •  眼角桃花
    2020-12-15 12:19

    You can insert your validation method within any document ready block, like the one shown below.

    $().ready(function() {
    
        $.validator.addMethod("lessThan",
            function(value, element, param) {
                var i = parseFloat(value);
                var j = parseFloat(param);
                return (i < j) ? true : false;
            }
        );
    
    });
    

    I've tried to keep this simple so that you can modify it. If the method is called "lessThan" then it should do just that. If your method actually performs "less than or Equal To" consider a more appropriate name.

    Please note that I am also using parseFloat, allowing the method more flexibility than parseInt.

    From within your validator, you were using it correctly; so for a validation of say, less than 10:

    $('#myForm').validate({ rules: { value1: { lessThan: "10"}} });
    

    Good luck!

提交回复
热议问题