I have a few sets of min and max fields in a form, where the user can specify a range by filling in a min and a max. I\'m using jQuery\'s Validate plugin for my form validat
Simple and good way to use addmethod
$.validator.addMethod("greaterThan",
function (value, element, param) {
var $min = $(param);
if (this.settings.onfocusout) {
$min.off(".validate-greaterThan").on("blur.validate-greaterThan", function () {
$(element).valid();
});
}
return parseInt(value) > parseInt($min.val());
}, "Must be greater than to field 1");
validating code
filed2_name: {
greaterThan: '#filed1_id'
},
second i prefer first
$.validator.addMethod('le', function(value, element, param) {
return this.optional(element) || value <= $(param).val();
}, 'Invalid value');
$.validator.addMethod('ge', function(value, element, param) {
return this.optional(element) || value >= $(param).val();
}, 'Invalid value');
$('form').validate({rules: {
fieldName1: {le: '#fieldID2'},
fieldName2: {ge: '#fieldID1'},
...
},
messages: {
fieldName1: {le: 'Must be less than or equal to field 2'},
fieldName2: {ge: 'Must be greater than or equal to field 1'},
...
}
});