首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Bootstrap 表單驗證最佳實踐:BootstrapValidator 插件完整接入指南

     編輯:程式設計疑難解答

Bootstrap 本身僅提供驗證狀態樣式(`.has-success`、`.has-error`、圖標),不包含驗證邏輯。生產環境推薦使用功能完善的 BootstrapValidator (現更名為 bootstrap-validator 或 FormValidation)。

快速接入步驟

  1. 引入文件:
    <link href="css/bootstrapValidator.min.css" rel="stylesheet">
    <script src="js/bootstrapValidator.min.js"></script>
  2. 表單添加標識:
    <form id="registerForm" method="post" class="form-horizontal">
      <div class="form-group">
        <label class="col-sm-3 control-label">郵箱</label>
        <div class="col-sm-5">
          <input type="email" class="form-control" name="email" />
        </div>
      </div>
      <!-- 更多字段 -->
    </form>
  3. JS 初始化:
    $('#registerForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            email: {
                validators: {
                    notEmpty: { message: '郵箱不能為空' },
                    emailAddress: { message: '郵箱格式不正確' }
                }
            },
            phone: {
                validators: {
                    notEmpty: { message: '手機號不能為空' },
                    regexp: { regexp: /^1[3-9]\d{9}$/, message: '手機號格式錯誤' }
                }
            },
            username: {
                validators: {
                    notEmpty: { message: '用戶名不能為空' },
                    stringLength: { min: 3, max: 20, message: '長度 3-20' },
                    regexp: { regexp: /^[a-zA-Z0-9_]+$/, message: '只能字母數字下劃線' },
                    remote: { url: '/checkUser', message: '用戶名已存在' }  // 異步驗證
                }
            }
        }
    });

核心驗證器速查

驗證器用途示例
notEmpty非空{}
stringLength長度範圍{min: 6, max: 30}
regexp正則{regexp: /^[a-z]+$/}
emailAddress郵箱格式{}
identical與某字段相同{field: 'password'}
remote異步服務端驗證{url: '/api/check', type: 'POST'}
callback自定義函數{callback: function(v, $f) { return v > 10; }}

進階技巧

  • 動態添加字段:`$form.bootstrapValidator('addField', 'newField', {...})`
  • 手動觸發驗證:`$form.data('bootstrapValidator').validate()`
  • 重置表單:`$form.data('bootstrapValidator').resetForm(true)`
  • 提交前攔截:監聽 `success.form.bv` 事件,阻止默認提交,改用 AJAX
官方示例與文檔:BootstrapValidator 中文教程 | FormValidation Bootstrap 範例
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved