bootrap select2 和 jquery.validate 集成
HTML
<div class="container"> <form method="post" id="documentAdmin"> <div class="form-group"> <label for="metals">Metals:</label> <select id="metals" name="metals" class="form-control required" aria-required="true" aria-invalid="false"> <option></option> <option value="Co">Cobalt</option> <option value="Ni">Nickel</option> <option value="Cu">Copper</option> <option value="Ag">Silver</option> <option value="Au">Gold</option> </select> </div> <div class="form-group"> <label for="gyr_ind">Colors:</label> <select id="gyr_ind" name="gyr_ind" class="select2 form-control required"> <option value="">select one</option> <option value="G">Green</option> <option value="Y">Yellow</option> <option value="R">Red</option> <option value="X">None</option> </select> </div> <button type="submit" class="btn btn-primary">Save</button> </form> </div>
JS
$.validator.setDefaults({ errorElement: "span", errorClass: "help-block", // validClass: 'stay', highlight: function (element, errorClass, validClass) { $(element).addClass(errorClass); //.removeClass(errorClass); $(element).closest('.form-group').removeClass('has-success').addClass('has-error'); }, unhighlight: function (element, errorClass, validClass) { $(element).removeClass(errorClass); //.addClass(validClass); $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); }, errorPlacement: function (error, element) { if (element.parent('.input-group').length) { error.insertAfter(element.parent()); } else if (element.hasClass('select2')) { error.insertAfter(element.next('span')); } else { error.insertAfter(element); } } }); $(document).ready(function () { $('.select2').on('change', function () { $(this).valid(); }); $("#gyr_ind").select2(); var validator = $("#documentAdmin").validate(); });
css
.has-error .select2-selection { border: 1px solid #a94442; border-radius: 4px; }
http://jsfiddle.net/z49mb6wr/1/
http://stackoverflow.com/questions/30783019/styling-jquery-validation-with-select2-4-0-and-bootstrap-3