Reputation: 31
I am trying to link two form fields using jQuery validate. The user can only enter up to 5 years, but this is spread over two inputs, months and years.
I have worked out to the following how I feel it should come together :
$('#leform')validate({
debug: true,
rules: {
years : {
required : {
depends: function(element) {
var x = ($('#years').val() == 5) && ($('#months').val() == 0),
y = ($('#years').val() < 5),
z = (x || y);
return z;
},
number : true,
max : 5,
min : 0
},
months : {
required : true,
number : true,
min: 0,
max: 11
}
}
});
The user can input, 3 years 6 months, no problem, but the issue lies when the user inputs 5 years, 4 months I cannot get the validation to fire. Any ideas?
-------- EDIT / SOLUTION ---------
Sorry im a pretty new user (long time lurker) so had to edit the question to post the answer
Ok so it turns out I was misinterpreting the spec, it looks like "required" is a boolean true or false.
I extended the validation with the following :
jQuery.validator.addMethod("yearCount", function(value, element) {
var x = ($('#years').val() == 5) && ($('#months').val() == 0),
y = ($('#years').val() < 5),
z = (x || y);
return z;
}, "blah blah blah");
and updated the rules as follows :
required : true,
max : 5,
min : 0,
yearCount : true
Upvotes: 2
Views: 4050
Reputation: 2991
This may help:
$('#leform').validate({
debug: true,
rules: {
years : {
required : {
depends: function(element) {
return (($(element).val() == 5 && $('#months').val() == 0) || ($(element).val() < 5));
},
number : true,
max : 5,
min : 0
},
months : {
required : true,
number : true,
min: 0,
max: 11
}
}
}
});
Upvotes: 0
Reputation: 272246
I think you can use the following function for the depends:
property for both controls:
function (){
return $('#years').val() * 12 + $('#months').val() * 1 <= 60;
}
Upvotes: 2