Reputation: 3958
I am currently working on a project what has the following code
$('form').validate({
rules: {
....
'final_input': {
require:true
}
},
ignore: ':hidden'
});
I have a custom dropdown list plugin which will be generated based on a hidden input. the code will look like
<input type="checkbox" />
<div id="dropdownlist" style="display: none">
<div class="option"></div>
<div class="option"></div>
<div class="option"></div>
<input id="final_input" name="final_input" type="text" style="display: none" />
</div>
the dropdownlist is also hidden until checkbox is checked. currently, it will ignore all hidden elements. so my final_input will not be validated. if I put something in ignore like :hidden:not('#final_input'). it will validate it no matter what. however I only want to validate it when the dropdownlist is visible. does anyone know how I can exclude the final_input from the ignore only when the dropdownlist in visible? or the checkbox is checked?
Upvotes: 0
Views: 1281
Reputation: 98738
Rather that messing around with including/excluding hidden input elements, use the depends
method to make the required
rule depend on something else.
For simplicity of demonstration, my example does not use a custom drop-down, however, you can use one and my approach will work the same. To disable the ignoring of all hidden fields, use ignore: []
.
In this basic demo, the text field is only required
when the checkbox is ticked or the drop-down is visible.
ignore: [], // <-- do not ignore any hidden fields
rules: {
final_input: {
required: {
depends: function () {
return ( $('#dropdownlist').is(':visible') || $('#check').is(':checked') );
}
}
}
}
DEMO (invisible select): http://jsfiddle.net/AZYpf/
Same DEMO (visible select): http://jsfiddle.net/AZYpf/1/
Custom selectors: http://jqueryvalidation.org/category/selectors/
Upvotes: 1