使用jQuery Validation插件的Bootstrap我正在嘗試使用jQuery Validation Plugin為我的表單添加驗證,但我遇到的問題是,當我使用輸入組時,插件會放置錯誤消息。$('form').validate({
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
}});我的代碼: http ://jsfiddle.net/hTPY7/4/
3 回答

繁花如伊
TA貢獻2012條經驗 獲得超12個贊
為了與Bootstrap 3完全兼容,我添加了對輸入組,無線電和復選框的支持,這在其他解決方案中是缺失的。
檢查了其他答案的建議,并為無線電內聯的特殊標記添加了額外支持,為一組無線電或復選框提供了更好的錯誤放置,并添加了對自定義.novalidation類的支持,以防止對控件進行驗證。希望這有助于并感謝您的建議。
包含驗證插件后添加以下調用:
$.validator.setDefaults({ errorElement: "span", errorClass: "help-block", highlight: function (element, errorClass, validClass) { // Only validation controls if (!$(element).hasClass('novalidation')) { $(element).closest('.form-group').removeClass('has-success').addClass('has-error'); } }, unhighlight: function (element, errorClass, validClass) { // Only validation controls if (!$(element).hasClass('novalidation')) { $(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.prop('type') === 'radio' && element.parent('.radio-inline').length) { error.insertAfter(element.parent().parent()); } else if (element.prop('type') === 'checkbox' || element.prop('type') === 'radio') { error.appendTo(element.parent().parent()); } else { error.insertAfter(element); } }});
這適用于所有Bootstrap 3表單類。如果使用水平形式,則必須使用以下標記。這可確保幫助塊文本遵循表單組的驗證狀態(“has-error”,...)。
<div class="form-group"> <div class="col-lg-12"> <div class="checkbox"> <label id="LabelConfirm" for="CheckBoxConfirm"> <input type="checkbox" name="CheckBoxConfirm" id="CheckBoxConfirm" required="required" /> I have read all the information </label> </div> </div></div>
- 3 回答
- 0 關注
- 583 瀏覽
添加回答
舉報
0/150
提交
取消