DIV CSS 佈局教程網

Bootstrap Validator 表單驗證的使用方式
編輯:關於JavaScript     

Bootstrap Validator 是搭配 Bootstrap 使用的表單驗證外掛,以宣告式設定描述規則,並自動套用樣式與錯誤提示。線上文件與 demo 可參考 BootstrapValidator 文件。

HTML 結構

 <form id="defaultForm" method="post" class="form-horizontal" action="target.php"> <div class="form-group"> <label class="col-lg-3 control-label">用戶名</label> <div class="col-lg-5"> <input type="text" class="form-control" name="username" /> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">郵箱</label> <div class="col-lg-5"> <input type="text" class="form-control" name="email" /> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">生日</label> <div class="col-lg-5"> <input type="text" class="form-control" name="birthday" /> (YYYY/MM/DD) </div> </div> <div class="form-group"> <div class="col-lg-9 col-lg-offset-3"> <button type="submit" class="btn btn-primary" name="signup" value="Sign up">提交</button> <button type="button" class="btn btn-info" id="validateBtn">自動驗證</button> <button type="button" class="btn btn-info" id="resetBtn">重置表單</button> </div> </div> </form>

這裡有個關鍵前提:每個要被驗證的欄位都必須有 name 屬性,因為 Validator 是依 name 來對應規則的,少了它就完全不會被檢查。

驗證設定

 $('#defaultForm').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid:      'glyphicon glyphicon-ok', invalid:    'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { username: { message: 'The username is not valid', validators: { notEmpty: { message: 'The username is required and cannot be empty' }, stringLength: { min: 6, max: 30, message: 'The username must be more than 6 and less than 30 characters long' }, regexp: { regexp: /^[a-zA-Z0-9_\.]+$/, message: 'The username can only consist of alphabetical, number, dot and underscore' }, remote: { url: 'remote.php', message: 'The username is not available' }, different: { field: 'password', message: 'The username and password cannot be the same as each other' } } }, email: { validators: { emailAddress: { message: 'The input is not a valid email address' } } }, } });

幾個實務重點

1. 驗證器是可堆疊的。 同一個欄位可以掛多個 validator,它們會依序執行,全部通過才算成功。這讓「必填 + 長度 + 格式 + 唯一性」可以拆成四段獨立設定,各自有專屬訊息,維護起來比一大段 if-else 清楚得多。

2. remote 驗證要節流。 remote 會在每次輸入後請求出伺服器確認(例如帳號是否已被註冊)。若不加 debounce,會產生大量請求;同時後端也要做好速率限制。

3. 記得在成功後才送出。 Validator 會攔下 submit 事件,若要自訂流程,可監聽 success.form.bv 事件再發出請求。

4. 選擇替代方案。 Bootstrap Validator 最後的官方維護停在 Bootstrap 3 時期,作者後續另起 Bootstrap 4 相容的分支。新專案若使用 Bootstrap 5,建議評估改用 HTML5 原生驗證 API(required、pattern、checkValidity())搭配 Constraint Validation,或採用仍在維護的表單驗證函式庫,以免日後無人修復相容問題。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved