實用方法
1.引入
在有jquery和bootstrap的頁面里引入bootstrapValidator.js和bootstrapValidator.css文件
2. 按照bootstrap的表單組件 構建html代碼
在表單中,若對某一字段想添加驗證規則,默認需要以<div class=”form-group”></div>包裹(對應錯誤提示會根據該class值定位),內部<input class="form-control" />標簽必須有name屬性值,此值為驗證匹配字段。
<form id="loginForm">
<div class="form-group">
<label for="username">管理員</label>
<input name="username" type="text" class="form-control" id="username" placeholder="請輸入用戶名">
</div>
<div class="form-group">
<label for="password">密碼</label>
<input name="password" type="password" class="form-control" id="password" placeholder="請輸入密碼">
</div>
<button type="reset" class="btn btn-default">重置</button>
<button type="submit" class="btn btn-primary">登錄</button>
</form>
3.找到需要做校驗的表單 初始化校驗插件方法
$('#loginForm').bootstrapValidator({
/*根據驗證結果顯示的各種圖標*/
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
/*去校驗表單元素 用戶名 密碼*/
/*校驗狀態:未校驗 NOT_VALIDATED 正在校驗 VALIDATING 校驗成功 VALID 校驗失敗 INVALID */
/*校驗規則:是需要去配置*/
/* fields 字段 ---> 表單內的元素*/
fields:{
/*指定需要校驗的元素 通過name數據去指定*/
username:{
/*配置校驗規則 規則不止一個*/
validators:{
/*配置具體的規則*/
notEmpty:{
/*校驗不成功的提示信息*/
message:'請您輸入用戶名'
},
/*自定義規則*/
callback:{
message:'用戶名錯誤'
}
}
},
password:{
validators:{
notEmpty:{
message:'請您輸入密碼'
},
stringLength:{
min:6,
max:18,
message:'密碼6-18個字符'
},
/*自定義規則*/
callback:{
message:'密碼錯誤'
}
}
}
}
/*當校驗失敗 默認阻止了提交*/
/*當校驗成功 默認就提交了*/
/*阻止默認的提交方式 改用ajax提交方式*/
}).on('success.form.bv',function (e) {
/*阻止瀏覽器默認行為*/
e.preventDefault();
var $form = $(e.target);
/*發登錄請求*/
$.ajax({
type:'post',
url:'/employee/employeeLogin',
/*可傳遞的數據格式 對象 序列化后的數據 key=value的字符串 [{name:'',value},...] */
data:$form.serialize(),
dataType:'json',
success:function (data) {
/*響應成功后的邏輯*/
if(data.success){
location.href = '/admin/index.html';
}else{
if(data.error == 1000){
/*調用校驗插件 讓該選項置為 校驗失敗狀態 提示校驗失敗的信息*/
/*updateStatus(‘哪個元素’,‘修改為什么狀態’,‘校驗規則’)*/
$form.data('bootstrapValidator').updateStatus('username','INVALID','callback')
}else if(data.error == 1001){
$form.data('bootstrapValidator').updateStatus('password','INVALID','callback')
}
}
}
});
});
