jQuery validate less than
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!
I'm an idiot. I had made some typo's in my actual code and I'd messed up the this.optional(element) that I see in a lot of validator methods. Here is the working function:
$.validator.addMethod('lessThanEqual', function(value, element, param) {
if (this.optional(element)) return true;
var i = parseInt(value);
var j = parseInt($(param).val());
return i <= j;
}, "The value {0} must be less than {1}");
Here is the condensed version
$.validator.addMethod('lessThanEqual', function(value, element, param) {
return this.optional(element) || parseInt(value) <= parseInt($(param).val());
}, "The value {0} must be less than {1}");
Now I need to figure out how to rerun validation for field 1 when I change field2.
I think you can do that without actually writing your own validator method.
$('#myForm').validate({
rules: {
value1: {
maxlength: $('#value2').val().length
}
}
});
$('#value2').change(function() {
$('#value1').rules('remove', 'maxlength').rules('add', {
maxlength: $('#value2').val().length
});
});
or even better without code duplication
function getRule() {
return {
maxlength: $('#value2').val().length
};
}
$('#myForm').validate({
rules: {
value1: getRule()
}
});
$('#value2').change(function() {
$('#value1').rules('remove', 'maxlength').rules('add', getRule());
});
Consider (A) is the name of the input that you want the value of it to be less than (#B) input.
this code worked with me after making the type of the two inputs is: type="number"
$("#form").validate({
rules: {
A: {
lessThan: "#B"
}
}
});