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 validation. I'd like to set up a validation rule that enforces that the max field is greater than the min. This would be invoked whenever the max or the min fields values are changed.
I know I can set up some sort of basic custom validation method like this:
$.validator.addMethod("greaterThan",
function(value, max, min){
return parseInt(value) > parseInt($(min).val());
}, "Max must be greater than min"
);
And then add a rule for the max element:
rules: {
maxTruck: {greaterThan: '#minTruck'}
}
But it's a bit more complicated because this only applies when the max field is changed, not the min. Is there any simple way to do this without having to write a lessThan method and apply that to the min field?
And then another thing I'd like to tackle - is there any simple way that I can apply this generically instead of having to enumerate each max field and which min it maps to? So that I can just have a min and max class and call something like:
$(".max").rules('add', { greaterThan: ".min" });
And somehow set up the method to be able to figure out (maybe based on a shared attribute?) which min the max field is paired with?
Update:
The basic logic that I mentioned in this post can be seen in this jsfiddle. However, I have not really worked on this much - I am looking for the logic to basically link sets of min and max fields the way I described. And I don't know if this is the best way to do this - as I mentioned, I'd love to be able to do this generically so that I don't have to refer to the min and max fields by id.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…