BootstrapValidator 是搭配 Bootstrap 使用的表單驗證插件,它能自動處理錯誤提示的位置與樣式,並支援擴充自訂規則。以下依序說明引入、HTML 結構、規則設定、自訂驗證與常用 API。
下載:https://github.com/nghuuphuoc/bootstrapvalidator/archive/v0.4.5.zip
<link rel="stylesheet" href="/path/to/bootstrap/css/bootstrap.css"/> <link rel="stylesheet" href="/path/to/dist/css/bootstrapValidator.min.css"/> <script type="text/javascript" src="/path/to/jquery/jquery.min.js"></script> <script type="text/javascript" src="/path/to/bootstrap/js/bootstrap.min.js"></script> <!-- 含大量常用預設驗證規則 --> <script type="text/javascript" src="/path/to/dist/js/bootstrapValidator-all.js"></script> <!-- 或:不含常用規則,需自行定義 --> <script type="text/javascript" src="/path/to/dist/js/bootstrapValidator.min.js"></script> <!-- 自訂規則檔 --> <script type="text/javascript" src="/path/to/dist/js/validator/myCustomRules.js"></script>
預設情況下,每個需要驗證的欄位都應包在 <div class="form-group"> 裡,插件會依此定位錯誤訊息;<input> 必須有 name 屬性,該值就是規則比對的欄位名。
<form class="form-horizontal">
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email address</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="email" />
</div>
</div>
</form>
這並非硬性規定,也可以透過 JS 的 selector 與 container 自行指定輸入框與提示位置。
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="username"
data-bv-message="The username is not valid"
required
data-bv-notempty-message="The username is required and cannot be empty"
pattern="[a-zA-Z0-9]+"
data-bv-regexp-message="The username can only consist of alphabetical, number" />
</div>
</div>
$(formSelector).bootstrapValidator({
/** 排除不驗證的元素,可為字串、陣列或帶回呼的陣列 */
excluded: [':disabled', ':hidden', ':not(:visible)'],
/** 驗證狀態圖示(Bootstrap 3.1.0 以上) */
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
/** 生效時機:enabled 為輸入即驗證;disabled / submitted 為送出時才驗證 */
live: 'enabled',
/** 通用錯誤提示文字 */
message: 'This value is not valid',
/** 提交按鈕選擇器,驗證未通過時會被 disable */
submitButtons: 'button[type="submit"]',
/** 驗證通過後的回呼,AJAX 送出表單時非常實用 */
submitHandler: function(validator, form, submitButton) {
$.post(form.attr('action'), form.serialize(), function(result) {
// 自訂回呼邏輯
}, 'json');
},
/** 全域觸發方式,可用 'focus blur keyup' */
trigger: null,
/** 輸入字數達標後才開始即時驗證 */
threshold: null,
fields: {
username: {
enabled: true,
message: 'This value is not valid',
container: null, // 錯誤提示位置,接受 CSS 選擇器
selector: null, // 自訂驗證的節點
trigger: null,
validators: {
notEmpty: { message: '用戶名不能為空' },
regexp: { regexp: /^[a-zA-Z0-9]+$/, message: '只能包含英數字' }
}
}
}
});
若 selector 用了帶中劃線的自訂屬性(如 [data-stripe="exp-month"]),對應的 fields 鍵名要轉成駝峰式(expMonth)。
做法是擴充插件的 validators:
(function($) {
$.fn.bootstrapValidator.validators = {
myRule: {
/**
* @param {BootstrapValidator} validator 表單驗證實例
* @param {jQuery} $field 目前欄位的 jQuery 物件
* @param {Object} options 該規則的設定值
* @returns {boolean}
*/
validate: function(validator, $field, options) {
var reg = new RegExp(options.pattern);
// 也可回傳 { valid: true/false, message: '...' }
return reg.test($field.val());
}
}
};
}(window.jQuery));
// 重設單一欄位的驗證狀態
$(formName).data("bootstrapValidator").updateStatus("fieldName", "NOT_VALIDATED", null);
// 重設整個表單
$(formName).data("bootstrapValidator").resetForm();
// 手動觸發驗證(全部或指定欄位)
$(formName).data("bootstrapValidator").validate();
$(formName).data("bootstrapValidator").validate('fieldName');
// 取得目前是否通過驗證
var flag = $(formName).data("bootstrapValidator").isValid();
// 依欄位名取得對應的 jQuery 物件
var element = $(formName).data("bootstrapValidator").getFieldElements('fieldName');
情況一:一般按鈕——需自行觸發驗證再決定是否送出。
$("buttonName").on("click", function(){
var bootstrapValidator = form.data('bootstrapValidator');
bootstrapValidator.validate();
if(bootstrapValidator.isValid()){
// 送出邏輯,例如 AJAX
}
});
情況二:type="submit"——插件會在 success.form.bv 之前自動驗證,攔下預設行為即可:
var bootstrapValidator = form.data('bootstrapValidator');
bootstrapValidator.on('success.form.bv', function (e) {
e.preventDefault();
// 提交邏輯
});
最後提醒:前端驗證只是使用者體驗,伺服器端一定要再驗一次。任何規則都能被 DevTools 繞過,安全不能只靠前端。