js-BootstrapValidator簡單使用


本例使用版本

 <!-- 新 Bootstrap 核心 CSS 文件 -->
  <link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <link href="http://cdn.bootcss.com/bootstrap-validator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
  <link href="./index.css" rel="stylesheet">
  <!-- jQuery文件。務必在bootstrap.min.js 之前引入 -->
  <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
 
  <!-- 最新的 Bootstrap 核心 JavaScript 文件
   -->
  <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="http://cdn.bootcss.com/bootstrap-validator/0.5.3/js/bootstrapValidator.min.js"></script>

默認 規則:

1.應在對應提示位置需要顯示信息,故在使用某個文本等需要校驗是需要

默認需要以<div class=”form-group”></div>包裹

 

2.使用定位到某個文本要校驗時已name的值為唯一指向

<input class="form-control" />標簽必須有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>

 

 

綁定規則案例

html如下

<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>

 

綁定js

$(formSelector).bootstrapValidator({
    /**
    *  指定不驗證的情況
    *  值可設置為以下三種類型:
    *  1、String  ':disabled, :hidden, :not(:visible)'
    *  2、Array  默認值  [':disabled', ':hidden', ':not(:visible)']
    *  3、帶回調函數  
        [':disabled', ':hidden', function($field, validator) {
            // $field 當前驗證字段dom節點
            // validator 驗證實例對象 
            // 可以再次自定義不要驗證的規則
            // 必須要return,return true or false; 
            return !$field.is(':visible');
        }]
    */
    excluded: [':disabled', ':hidden', ':not(:visible)'],
    /**
    * 指定驗證后驗證字段的提示字體圖標。(默認是bootstrap風格)
    * Bootstrap 版本 >= 3.1.0
    * 也可以使用任何自定義風格,只要引入好相關的字體文件即可
    * 默認樣式 
        .form-horizontal .has-feedback .form-control-feedback {
            top: 0;
            right: 15px;
        }
    * 自定義該樣式覆蓋默認樣式
        .form-horizontal .has-feedback .form-control-feedback {
            top: 0;
            right: -15px;
        }
        .form-horizontal .has-feedback .input-group .form-control-feedback {
            top: 0;
            right: -30px;
        }
    */
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    /**
    * 生效規則(三選一)
    * enabled 字段值有變化就觸發驗證
    * disabled,submitted 當點擊提交時驗證並展示錯誤信息
    */
    live: 'enabled',
    /**
    * 為每個字段指定通用錯誤提示語
    */
    message: 'This value is not valid',
    /**
    * 指定提交的按鈕,例如:'.submitBtn' '#submitBtn'
    * 當表單驗證不通過時,該按鈕為disabled
    */
    submitButtons: 'button[type="submit"]',
    /**
    * submitHandler: function(validator, form, submitButton) {
    *   //validator: 表單驗證實例對象
    *   //form  jq對象  指定表單對象
    *   //submitButton  jq對象  指定提交按鈕的對象
    * }
    * 在ajax提交表單時很實用
    *   submitHandler: function(validator, form, submitButton) {
            // 實用ajax提交表單
            $.post(form.attr('action'), form.serialize(), function(result) {
                // .自定義回調邏輯
            }, 'json');
         }
    * 
    */
    submitHandler: null,
    /**
    * 為每個字段設置統一觸發驗證方式(也可在fields中為每個字段單獨定義),默認是live配置的方式,數據改變就改變
    * 也可以指定一個或多個(多個空格隔開) 'focus blur keyup'
    */
    trigger: null,
    /**
    * Number類型  為每個字段設置統一的開始驗證情況,當輸入字符大於等於設置的數值后才實時觸發驗證
    */
    threshold: null,
    /**
    * 表單域配置
    */
    fields: {
        //多個重復
        <fieldName>: {
            //隱藏或顯示 該字段的驗證
            enabled: true,
            //錯誤提示信息
            message: 'This value is not valid',
            /**
            * 定義錯誤提示位置  值為CSS選擇器設置方式
            * 例如:'#firstNameMeg' '.lastNameMeg' '[data-stripe="exp-month"]'
            */
            container: null,
            /**
            * 定義驗證的節點,CSS選擇器設置方式,可不必須是name值。
            * 若是id,class, name屬性,<fieldName>為該屬性值
            * 若是其他屬性值且有中划線鏈接,<fieldName>轉換為駝峰格式  selector: '[data-stripe="exp-month"]' =>  expMonth
            */
            selector: null,
            /**
            * 定義觸發驗證方式(也可在fields中為每個字段單獨定義),默認是live配置的方式,數據改變就改變
            * 也可以指定一個或多個(多個空格隔開) 'focus blur keyup'
            */
            trigger: null,
            // 定義每個驗證規則
            validators: {
                //多個重復
                //官方默認驗證參照  http://bv.doc.javake.cn/validators/
                // 注:使用默認前提是引入了bootstrapValidator-all.js
                // 若引入bootstrapValidator.js沒有提供常用驗證規則,需自定義驗證規則哦
                <validatorName>: <validatorOptions>
            }
        }
    }
});

 

 

自定義校驗規則如下

(function($) {
    //自定義表單驗證規則
    $.fn.bootstrapValidator.validators = {
        <validatorName> : {
            /**
             * @param {BootstrapValidator} 表單驗證實例對象
             * @param {jQuery} $field jQuery 對象
             * @param {Object} 表單驗證配置項值
             * @returns {boolean}
             */
            validate: function(validator, $field, options) {
                // 表單輸入的值
                // var value = $field.val();

                //options為<validatorOptions>對象,直接.獲取需要的值

                // 返回true/false
                //也可返回{ valid : true/false, message: 'XXXX'}
                return reg.test( $field.val() );

            }
        },
    };
}(window.jQuery));

 

 

其他重要事件

1、重置某一單一驗證字段驗證規則

$(formName).data(“bootstrapValidator”).updateStatus("fieldName",  "NOT_VALIDATED",  null );

 

2、重置表單所有驗證規則

$(formName).data("bootstrapValidator").resetForm();

 

3、手動觸發表單驗證

//觸發全部驗證
$(formName).data(“bootstrapValidator”).validate();
//觸發指定字段的驗證
$(formName).data(“bootstrapValidator”).validate('fieldName');

 

4、獲取當前表單驗證狀態

// flag = true/false 
var flag = $(formName).data(“bootstrapValidator”).isValid();

 

5、根據指定字段名稱獲取驗證對象

// element = jq對象 / null
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之前自動觸發表單驗證

var bootstrapValidator = form.data('bootstrapValidator');
bootstrapValidator.on('success.form.bv', function (e) {
    e.preventDefault();
    //提交邏輯
});

 

 

 

各種校驗規則

             username: {//驗證input項:驗證規則
                 message: 'The username is not valid',
                
                 validators: {
                     notEmpty: {//非空驗證:提示消息
                         message: '用戶名不能為空'
                     },
                     stringLength: {
                         min: 6,
                         max: 30,
                         message: '用戶名長度必須在6到30之間'
                     },
                     threshold :  6 , //有6字符以上才發送ajax請求,(input中輸入一個字符,插件會向服務器發送一次,設置限制,6字符以上才開始)
                     remote: {//ajax驗證。server result:{"valid",true or false} 向服務發送當前input name值,獲得一個json數據。例表示正確:{"valid",true}  
                         url: 'exist2.do',//驗證地址
                         message: '用戶已存在',//提示消息
                         delay :  2000,//每輸入一個字符,就發ajax請求,服務器壓力還是太大,設置2秒發送一次ajax(默認輸入一個字符,提交一次,服務器壓力太大)
                         type: 'POST'//請求方式
                         /**自定義提交數據,默認值提交當前input value
                          *  data: function(validator) {
                               return {
                                   password: $('[name="passwordNameAttributeInYourForm"]').val(),
                                   whatever: $('[name="whateverNameAttributeInYourForm"]').val()
                               };
                            }
                          */
                     },
                     regexp: {
                         regexp: /^[a-zA-Z0-9_\.]+$/,
                         message: '用戶名由數字字母下划線和.組成'
                     }
                 }
             },
             password: {
                 message:'密碼無效',
                 validators: {
                     notEmpty: {
                         message: '密碼不能為空'
                     },
                     stringLength: {
                         min: 6,
                         max: 30,
                         message: '用戶名長度必須在6到30之間'
                     },
                     identical: {//相同
                         field: 'password', //需要進行比較的input name值
                         message: '兩次密碼不一致'
                     },
                     different: {//不能和用戶名相同
                         field: 'username',//需要進行比較的input name值
                         message: '不能和用戶名相同'
                     },
                     regexp: {
                         regexp: /^[a-zA-Z0-9_\.]+$/,
                         message: 'The username can only consist of alphabetical, number, dot and underscore'
                     }
                 }
             },
             repassword: {
                 message: '密碼無效',
                 validators: {
                     notEmpty: {
                         message: '用戶名不能為空'
                     },
                     stringLength: {
                         min: 6,
                         max: 30,
                         message: '用戶名長度必須在6到30之間'
                     },
                     identical: {//相同
                         field: 'password',
                         message: '兩次密碼不一致'
                     },
                     different: {//不能和用戶名相同
                         field: 'username',
                         message: '不能和用戶名相同'
                     },
                     regexp: {//匹配規則
                         regexp: /^[a-zA-Z0-9_\.]+$/,
                         message: 'The username can only consist of alphabetical, number, dot and underscore'
                     }
                 }
             },
             email: {
                 validators: {
                     notEmpty: {
                         message: '郵件不能為空'
                     },
                     emailAddress: {
                         message: '請輸入正確的郵件地址如:123@qq.com'
                     }
                 }
             },
             phone: {
                 message: 'The phone is not valid',
                 validators: {
                     notEmpty: {
                         message: '手機號碼不能為空'
                     },
                     stringLength: {
                         min: 11,
                         max: 11,
                         message: '請輸入11位手機號碼'
                     },
                     regexp: {
                         regexp: /^1[3|5|8]{1}[0-9]{9}$/,
                         message: '請輸入正確的手機號碼'
                     }
                 }
             },
             invite: {
                 message: '邀請碼',
                 validators: {
                     notEmpty: {
                         message: '邀請碼不能為空'
                     },
                     stringLength: {
                         min: 8,
                         max: 8,
                         message: '請輸入正確長度的邀請碼'
                     },
                     regexp: {
                         regexp: /^[\w]{8}$/,
                         message: '請輸入正確的邀請碼(包含數字字母)'
                     }
                 }
             },

 

 

 

 

另完整遠程校驗

$(function(){/* 文檔加載,執行一個函數*/
     $('#defaultForm').bootstrapValidator({
         message: 'This value is not valid',
         feedbackIcons: {/*input狀態樣式圖片*/
             valid: 'glyphicon glyphicon-ok',
             invalid: 'glyphicon glyphicon-remove',
             validating: 'glyphicon glyphicon-refresh'
         },
         fields: {/*驗證:規則*/
             username: {//驗證input項:驗證規則
                 message: 'The username is not valid',
                
                 validators: {
                     notEmpty: {//非空驗證:提示消息
                         message: '用戶名不能為空'
                     },
                     stringLength: {
                         min: 6,
                         max: 30,
                         message: '用戶名長度必須在6到30之間'
                     },
                     threshold :  6 , //有6字符以上才發送ajax請求,(input中輸入一個字符,插件會向服務器發送一次,設置限制,6字符以上才開始)
                     remote: {//ajax驗證。server result:{"valid",true or false} 向服務發送當前input name值,獲得一個json數據。例表示正確:{"valid",true}  
                         url: 'exist2.do',//驗證地址
                         message: '用戶已存在',//提示消息
                         delay :  2000,//每輸入一個字符,就發ajax請求,服務器壓力還是太大,設置2秒發送一次ajax(默認輸入一個字符,提交一次,服務器壓力太大)
                         type: 'POST'//請求方式
                         /**自定義提交數據,默認值提交當前input value
                          *  data: function(validator) {
                               return {
                                   password: $('[name="passwordNameAttributeInYourForm"]').val(),
                                   whatever: $('[name="whateverNameAttributeInYourForm"]').val()
                               };
                            }
                          */
                     },
                     regexp: {
                         regexp: /^[a-zA-Z0-9_\.]+$/,
                         message: '用戶名由數字字母下划線和.組成'
                     }
                 }
             },
             password: {
                 message:'密碼無效',
                 validators: {
                     notEmpty: {
                         message: '密碼不能為空'
                     },
                     stringLength: {
                         min: 6,
                         max: 30,
                         message: '用戶名長度必須在6到30之間'
                     },
                     identical: {//相同
                         field: 'password', //需要進行比較的input name值
                         message: '兩次密碼不一致'
                     },
                     different: {//不能和用戶名相同
                         field: 'username',//需要進行比較的input name值
                         message: '不能和用戶名相同'
                     },
                     regexp: {
                         regexp: /^[a-zA-Z0-9_\.]+$/,
                         message: 'The username can only consist of alphabetical, number, dot and underscore'
                     }
                 }
             },
             repassword: {
                 message: '密碼無效',
                 validators: {
                     notEmpty: {
                         message: '用戶名不能為空'
                     },
                     stringLength: {
                         min: 6,
                         max: 30,
                         message: '用戶名長度必須在6到30之間'
                     },
                     identical: {//相同
                         field: 'password',
                         message: '兩次密碼不一致'
                     },
                     different: {//不能和用戶名相同
                         field: 'username',
                         message: '不能和用戶名相同'
                     },
                     regexp: {//匹配規則
                         regexp: /^[a-zA-Z0-9_\.]+$/,
                         message: 'The username can only consist of alphabetical, number, dot and underscore'
                     }
                 }
             },
             email: {
                 validators: {
                     notEmpty: {
                         message: '郵件不能為空'
                     },
                     emailAddress: {
                         message: '請輸入正確的郵件地址如:123@qq.com'
                     }
                 }
             },
             phone: {
                 message: 'The phone is not valid',
                 validators: {
                     notEmpty: {
                         message: '手機號碼不能為空'
                     },
                     stringLength: {
                         min: 11,
                         max: 11,
                         message: '請輸入11位手機號碼'
                     },
                     regexp: {
                         regexp: /^1[3|5|8]{1}[0-9]{9}$/,
                         message: '請輸入正確的手機號碼'
                     }
                 }
             },
             invite: {
                 message: '邀請碼',
                 validators: {
                     notEmpty: {
                         message: '邀請碼不能為空'
                     },
                     stringLength: {
                         min: 8,
                         max: 8,
                         message: '請輸入正確長度的邀請碼'
                     },
                     regexp: {
                         regexp: /^[\w]{8}$/,
                         message: '請輸入正確的邀請碼(包含數字字母)'
                     }
                 }
             },
         }
     })
     .on('success.form.bv', function(e) {//點擊提交之后
         // Prevent form submission
         e.preventDefault();

         // Get the form instance
         var $form = $(e.target);

         // Get the BootstrapValidator instance
         var bv = $form.data('bootstrapValidator');

         // Use Ajax to submit form data 提交至form標簽中的action,result自定義
         $.post($form.attr('action'), $form.serialize(), function(result) {
//do something...
});
     });
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM