1. 程式人生 > 程式設計 >Bootstrap簡單實用的表單驗證外掛BootstrapValidator用法例項詳解

Bootstrap簡單實用的表單驗證外掛BootstrapValidator用法例項詳解

本文例項講述了Bootstrap簡單實用的表單驗證外掛BootstrapValidator用法。分享給大家供大家參考,具體如下:

Bootstrap是現在非常流行的一款前端框架,這篇來介紹一款基於Bootstrap的驗證外掛BootstrapValidator。

先來看一下效果圖(樣式是不是還不錯O(∩_∩)O哈哈~)。

Bootstrap簡單實用的表單驗證外掛BootstrapValidator用法例項詳解

Bootstrapvalidator下載地址:https://github.com/nghuuphuoc/bootstrapvalidator/?

引入對應的CSS和JS

<link rel="stylesheet" type="text/css" href="css/bootstrap.css" rel="external nofollow" />
<link rel="stylesheet" type="text/css" href="css/bootstrapValidator.css" rel="external nofollow" />
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="js/bootstrap.js" type="text/javascript"></script>
<script src="js/bootstrapValidator.js"></script>

新增驗證規則

使用HTML新增驗證。

對某一個標籤新增驗證規則,需要放在<div class="form-group"></div>標籤中,input標籤必須有name屬性值,此值為驗證匹配的欄位。其實就是要符合bootstrap表單結構。

<div class="form-group">
  <label class="col-md-2 control-label">學號</label>
  <div class="col-md-6">
    <input type="text" class="form-control" name="stuNumber" data-bv-notempty="true" data-bv-notempty-message="使用者名稱不能為空" />
  </div>
</div>

初始化bootstrapValidator。

<script type="text/javascript">
$('form').bootstrapValidator({
  //預設提示
  message: 'This value is not valid',// 表單框裡右側的icon
  feedbackIcons: {
    valid: 'glyphicon glyphicon-ok',invalid: 'glyphicon glyphicon-remove',validating: 'glyphicon glyphicon-refresh'
  },submitHandler: function (validator,form,submitButton) {
    // 表單提交成功時會呼叫此方法
    // validator: 表單驗證例項物件
    // form jq物件 指定表單物件
    // submitButton jq物件 指定提交按鈕的物件
  }
});
</script>

效果圖。

Bootstrap簡單實用的表單驗證外掛BootstrapValidator用法例項詳解

使用data-bv-notempty 和 data-bv-notempty-message屬性就可以簡單進行非空驗證。data-bv-notempty 有值就進行非空驗證,data-bv-notempty-message 中的值為提示訊息。

使用JS新增驗證

HTML樣式程式碼。

<div class="form-group">
  <label class="col-md-2 control-label">姓名</label>
  <div class="col-md-6">
    <input type="text" class="form-control" name="name" />
  </div>
</div>
<div class="form-group">
  <label class="col-md-2 control-label">年齡</label>
  <div class="col-md-6">
    <input type="text" class="form-control" name="age" />
  </div>
</div>
<div class="form-group">
  <label class="col-md-2 control-label">電話</label>
  <div class="col-md-6">
    <input type="text" class="form-control" name="phoneNumber" />
  </div>
</div>
<div class="form-group">
  <label class="col-md-2 control-label">Email</label>
  <div class="col-md-6">
    <input type="text" class="form-control" name="email" />
  </div>
</div>
<div class="form-group">
  <label class="col-md-2 control-label">密碼</label>
  <div class="col-md-6">
    <input type="text" class="form-control" name="pwd" />
  </div>
</div>
<div class="form-group">
  <label class="col-md-2 control-label">確定密碼</label>
  <div class="col-md-6">
    <input type="text" class="form-control" name="pwd1" />
  </div>
</div>

JS驗證程式碼,其中fields屬性中的值,需要和HTML標籤中的name值一樣,確定給那個標籤新增驗證。

<script type="text/javascript">
  $('form').bootstrapValidator({
    //預設提示
    message: 'This value is not valid',// 表單框裡右側的icon
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',validating: 'glyphicon glyphicon-refresh'
    },submitButton) {
      // 表單提交成功時會呼叫此方法
      // validator: 表單驗證例項物件
      // form jq物件 指定表單物件
      // submitButton jq物件 指定提交按鈕的物件
    },fields: {
      username: {
        message: '使用者名稱驗證失敗',validators: {
          notEmpty: {   //不能為空
            message: '使用者名稱不能為空'
          },remote: {  //後臺驗證,比如查詢使用者名稱是否存在
            url: 'student/verifyUsername',message: '此使用者名稱已存在'
          }
        }
      },name: {
        message: '姓名驗證失敗',validators: {
          notEmpty: {
            message: '姓名不能為空'
          }
        }
      },age: {
        message: '年齡驗證失敗',validators: {
          notEmpty: {
            message: '年齡不能為空'
          },numeric: {
            message: '請填寫數字'
          }
        }
      },phoneNumber: {
        message: '電話號驗證失敗',validators: {
          notEmpty: {
            message: '電話號不能為空'
          },regexp: {  //正則驗證
            regexp: /^1\d{10}$/,message: '請輸入正確的電話號'
          }
        }
      },email: {
        message: 'Email驗證失敗',validators: {
          notEmpty: {
            message: 'Email不能為空'
          },emailAddress: {   //驗證email地址
            message: '不是正確的email地址'
          }
        }
      },pwd: {
        notEmpty: {
          message: '密碼不能為空'
        },stringLength: {   //檢測長度
          min: 4,max: 15,message: '使用者名稱需要在4~15個字元'
        }
      },pwd1: {
        message: '密碼驗證失敗',validators: {
          notEmpty: {
            message: '密碼不能為空'
          },identical: {  //與指定控制元件內容比較是否相同,比如兩次密碼不一致
            field: 'pwd',//指定控制元件name
            message: '兩次密碼不一致'
          }
        }
      }
    }
  });
</script>

效果如下。

Bootstrap簡單實用的表單驗證外掛BootstrapValidator用法例項詳解

AJAX後臺互動驗證,驗證使用者名稱是否存在。

<div class="form-group">
  <label class="col-md-2 control-label">使用者名稱</label>
  <div class="col-md-6">
    <input type="text" class="form-control" name="username" />
  </div>
</div>
 
<script type="text/javascript">
$('form').bootstrapValidator({
  //預設提示
  message: 'This value is not valid',submitButton) {
    // 表單提交成功時會呼叫此方法
    // validator: 表單驗證例項物件
    // form jq物件 指定表單物件
    // submitButton jq物件 指定提交按鈕的物件
  },fields: {
    username: {
      message: '使用者名稱驗證失敗',validators: {
        notEmpty: {   //不能為空
          message: '使用者名稱不能為空'
        },remote: {  //後臺驗證,比如查詢使用者名稱是否存在
          url: 'student/verifyUsername',message: '此使用者名稱已存在'
        }
      }
    }
  }
});
</script>

後臺驗證返回格式必須為{“valid”,true or false} 的json資料格式。後臺verifyUsername驗證判斷方法。

@RequestMapping(value="/verifyUsername")
@ResponseBody
public Map verifyUsername(String username){
  Student stu = studentService.findByUsername(username);
  Map map = new HashMap();
  if (stu == null) {
    map.put("valid",true);
  }else{
    map.put("valid",false);
  }
  return map;
}

效果如下。

Bootstrap簡單實用的表單驗證外掛BootstrapValidator用法例項詳解

下面是幾個比較常見的驗證規則。

  • notEmpty:非空驗證;
  • stringLength:字串長度驗證;
  • regexp:正則表示式驗證;
  • emailAddress:郵箱地址驗證(都不用我們去寫郵箱的正則了~~)
  • base64:64位編碼驗證;
  • between:驗證輸入值必須在某一個範圍值以內,比如大於10小於100;
  • creditCard:身份證驗證;
  • date:日期驗證;
  • ip:IP地址驗證;
  • numeric:數值驗證;
  • url:url驗證;
  • callback:自定義驗證
  • Form表單的提交

關於提交,可以直接用form表單提交即可。

<div class="form-group">
  <div class="col-md-6 col-md-offset-2">
    <button id="btn" type="submit" class="btn btn-primary">提交</button>
  </div>
</div>

也可以通過AJAX提交,提交按鈕程式碼和form表單的提交按鈕程式碼一樣,通過id選中按鈕繫結點選事件提交。

$("#btn").click(function () {  //非submit按鈕點選後進行驗證,如果是submit則無需此句直接驗證
  $("form").bootstrapValidator('validate');  //提交驗證
  if ($("form").data('bootstrapValidator').isValid()) {  //獲取驗證結果,如果成功,執行下面程式碼
    alert("yes");  //驗證成功後的操作,如ajax
  }
});

效果圖,這裡驗證通過後通過彈框提示的,方法中可以寫AJAX提交程式碼。

Bootstrap簡單實用的表單驗證外掛BootstrapValidator用法例項詳解

頁面完整程式碼。

<meta charset="UTF-8">
<form action="" class="form-horizontal">
  <div class="form-group">
    <label class="col-md-2 control-label">學號</label>
    <div class="col-md-6">
      <input type="text" class="form-control" name="stuNumber" data-bv-notempty="true" data-bv-notempty-message="使用者名稱不能為空" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-md-2 control-label">使用者名稱</label>
    <div class="col-md-6">
      <input type="text" class="form-control" name="username" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-md-2 control-label">姓名</label>
    <div class="col-md-6">
      <input type="text" class="form-control" name="name" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-md-2 control-label">年齡</label>
    <div class="col-md-6">
      <input type="text" class="form-control" name="age" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-md-2 control-label">電話</label>
    <div class="col-md-6">
      <input type="text" class="form-control" name="phoneNumber" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-md-2 control-label">Email</label>
    <div class="col-md-6">
      <input type="text" class="form-control" name="email" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-md-2 control-label">密碼</label>
    <div class="col-md-6">
      <input type="text" class="form-control" name="pwd" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-md-2 control-label">確定密碼</label>
    <div class="col-md-6">
      <input type="text" class="form-control" name="pwd1" />
    </div>
  </div>
  <div class="form-group">
    <div class="col-md-6 col-md-offset-2">
      <button id="btn" type="submit" class="btn btn-primary">提交</button>
    </div>
  </div>
</form>
 
<script type="text/javascript">
  $(function () {
    $('form').bootstrapValidator({
      //預設提示
      message: 'This value is not valid',// 表單框裡右側的icon
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',validating: 'glyphicon glyphicon-refresh'
      },submitButton) {
        // 表單提交成功時會呼叫此方法
        // validator: 表單驗證例項物件
        // form jq物件 指定表單物件
        // submitButton jq物件 指定提交按鈕的物件
      },fields: {
        username: {
          message: '使用者名稱驗證失敗',validators: {
            notEmpty: {   //不能為空
              message: '使用者名稱不能為空'
            },remote: {  //後臺驗證,比如查詢使用者名稱是否存在
              url: 'student/verifyUsername',message: '此使用者名稱已存在'
            }
          }
        },name: {
          message: '姓名驗證失敗',validators: {
            notEmpty: {
              message: '姓名不能為空'
            }
          }
        },age: {
          message: '年齡驗證失敗',validators: {
            notEmpty: {
              message: '年齡不能為空'
            },numeric: {
              message: '請填寫數字'
            }
          }
        },phoneNumber: {
          message: '電話號驗證失敗',validators: {
            notEmpty: {
              message: '電話號不能為空'
            },regexp: {  //正則驗證
              regexp: /^1\d{10}$/,message: '請輸入正確的電話號'
            }
          }
        },email: {
          message: 'Email驗證失敗',validators: {
            notEmpty: {
              message: 'Email不能為空'
            },emailAddress: {   //驗證email地址
              message: '不是正確的email地址'
            }
          }
        },pwd: {
          notEmpty: {
            message: '密碼不能為空'
          },stringLength: {   //檢測長度
            min: 4,message: '使用者名稱需要在4~15個字元'
          }
        },pwd1: {
          message: '密碼驗證失敗',validators: {
            notEmpty: {
              message: '密碼不能為空'
            },identical: {  //與指定控制元件內容比較是否相同,比如兩次密碼不一致
              field: 'pwd',//指定控制元件name
              message: '兩次密碼不一致'
            }
          }
        }
      }
    });
 
    $("#btn").click(function () {  //非submit按鈕點選後進行驗證,如果是submit則無需此句直接驗證
      $("form").bootstrapValidator('validate');  //提交驗證
      if ($("form").data('bootstrapValidator').isValid()) {  //獲取驗證結果,如果成功,執行下面程式碼
        alert("yes");  //驗證成功後的操作,如ajax
      }
    });
  })
</script>

到這裡,BootstrapValidator驗證外掛的方法已經寫的很全面了。不足地方歡迎大家下方留言指出!

可以使用線上HTML/CSS/JavaScript程式碼執行工具:http://tools.jb51.net/code/HtmlJsRun測試上述程式碼執行效果。

PS:關於bootstrap佈局,這裡再為大家推薦一款本站的線上視覺化佈局工具供大家參考使用:

線上bootstrap視覺化佈局編輯工具:
http://tools.jb51.net/aideddesign/layoutit

希望本文所述對大家基於bootstrap的程式設計有所幫助。