At work we build most websites using Bootstrap as the base for the responsive grid, Bootstrap-select to style HTML <select>
‘s and jQuery Validate for form validation. Turns out, the three of these don’t necessarily play well together out of the box.
jQuery Validate works in two ways. It starts off lazy by waiting for the user to submit a form, then if any fields are invalid it validates more eagerly, validating each field as the user edits it.
The lazy validation method works fine with Bootstrap-select but if jQuery Validate is validating eagerly, <select>
‘s using Bootstrap-select (selectpicker) will no longer validate because the eager validation method validates <select>
‘s on the focusout
event.
That’s all fine and good, right? Well it would be but unfortunately Bootstrap-select bypasses the focusout
event entirely, registering only a change
event. on the <select>
In order to get around this, force jQuery Validate to validate each <select>
on change
.
$('.validate-form select').on('change', function(e) { $('.validate-form').validate().element($(this)); });
Change validate-form
to be the class name of the form that you’re trying to validate (or add the class validate-form
to your validation form) and test!
But this will always validate the select picker even if the form is not submitted. So the first time form loads, if user tries with different options in select picker, it will validate that but the form is not submitted even single time.
That’s correct, it will validate the form when the select registers a
change
event. The form will not be submitted until the user clicks submit or whatever other method of submitting the form you provide.This is intentional, in most cases you wouldn’t want the form to submit until the user actually initiated a submission through a click. Submitting the form on a select change could cause confusion.
[…] I’ve mentioned before, we use jQuery Validate on most sites that we build at work. When validating forms it’s […]
Thanks for this little article, it was really helpful. I was using both jQuery Validate and Select and it was really annoying that after user submitted form without choosing the required select and then go back and choose one, error message is still shown. Fixed it with your tip. Thanks!!
Glad it was helpful!