I'm working with Bootstrap, selectpicker, and jQuery Validation plugins.
The Select List:
<div class="form-group" id="content">
<select id="country" name="country" required>
<option value=''>Select</option>
<option value='1'>USA</option>
</select>
</div>
The Selectpicker:
$('select').selectpicker();
To jQuery Validation need this to can see the Select List:
$('#frm-name').validate().settings.ignore = ':not(select:hidden, input:visible, textarea:visible)';
And then Validation:
$("#frm-name").validate({
rules: {
"country": {
required: true
}
},
errorPlacement: function(error, element) {
error.insertAfter("#content");
}
})
The error never shows.
What did I miss?
I'm not sure where you're going wrong with all this because it's working for me.
Some tips:
1) You don't need to use .validate().settings.ignore
when you can just use the ignore
option within your .validate()
call.
2) Although no harm is done, your field name
of country
does not need to be enclosed in quotes within .validate()
.
3) You do not need the required
attribute inside your <select>
element when you've already declared the required
rule within .validate()
.
4) When using the errorPlacement
callback function, take advantage of the error
and element
arguments since the same function is used generically for all of your form elements. By specifying the id
of a specific element, you'll be forcing all error messages for all input elements into the same exact location.
5) Since your select
element is hidden by the selectpicker
element and the selectpicker
element comes after the hidden select
, you'll need to adjust your jQuery to find the proper location in the DOM for your error placement.
Since your selectpicker
is the next element, element.next().after(error)
will insert the error message after the next element in the DOM tree. Use if ($(element).is('select'))
to test if the input is a select
element so as not to interfere with the error placement of the other input elements.
errorPlacement: function (error, element) {
if ($(element).is('select')) {
element.next().after(error); // special placement for select elements
} else {
error.insertAfter(element); // default placement for everything else
}
}
Full code:
$(document).ready(function () {
$('#country').selectpicker();
$("#frm-name").validate({
ignore: ':not(select:hidden, input:visible, textarea:visible)',
rules: {
country: {
required: true
}
},
errorPlacement: function (error, element) {
if ($(element).is('select')) {
element.next().after(error); // special placement for select elements
} else {
error.insertAfter(element); // default placement for everything else
}
}
})
});
Working DEMO: http://jsfiddle.net/Bccq7/