表單驗證是一個非常基礎的功能,當你的表單項少的時候,可以自己寫驗證,但是當你的表單有很多的時候,就需要一些驗證的插件。今天介紹一款很好用的表單驗證插件,formvalidation。其前身叫做bootstrapValidator.
下載:目前的最新版本是收費的,但是我們可以下載之前的版本。下載地址:http://down.htmleaf.com/1505/201505101833.zip
下載之后,解壓,整個文件夾里面除了最基本的js和css,還包含了很多實例,有興趣的可以自己去看看。接下來簡要介紹一下它的用法。
1.導入包
css:
<link rel="stylesheet" href="./static/formvalidation/vendor/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="./static/formvalidation/dist/css/formValidation.css">
js:
<script type="text/javascript" src="./static/formvalidation/vendor/jquery/jquery.min.js"></script> <script type="text/javascript" src="./static/formvalidation/vendor/bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript" src="./static/formvalidation/dist/js/formValidation.js"></script> <script type="text/javascript" src="./static/formvalidation/dist/js/framework/bootstrap.js"></script> <script type="text/javascript" src="./static/formvalidation/dist/js/language/zh_CN.js"></script>
需要注意的是,即便你已經在項目中導入了bootstrap.js,還是需要再導入上述的bootstrap.js文件,因為它和你之前導入的並不相同。
還有就是即便你已經導入了jquery.min.js,最好還是導入這邊的jquery.min.js,因為如果不導入,可能會導致remote類型的驗證失效。
2.表單
表單項的填寫需要遵從兩個原則,表單項的class需標記為:form-control。並且提交按鈕的id或者name不要設為sumbit,否則在驗證之后會出現無法提交的情況,一個典型的表單如下所示。
<form id="thisForm" method="post" action=""> <input type="hidden" name="type" value="1" /> <div class="container-fluid "> <div class="col-xs-12"> <div class="panel-body "> <div class="box box-danger box-padding"> <div class="row row-margin"> <div class="col-xs-8 col-xs-offset-1 tipinfo"> <div class="input-group"> <div class="input-group-btn"> <button type="button" class="btn btn-danger">合伙人賬號</button> </div> <!-- /btn-group --> <input type="text" class="form-control" name="partnerName"> </div> </div> </div> <div class="row row-margin"> <div class="col-xs-8 col-xs-offset-1 tipinfo"> <div class="input-group"> <div class="input-group-btn"> <button type="button" class="btn btn-danger">合伙人手機</button> </div> <!-- /btn-group --> <input type="text" class="form-control" name="phone"> </div> </div> </div> <div class="row row-margin"> <div class="col-xs-8 col-xs-offset-1 tipinfo"> <div class="input-group"> <div class="input-group-btn"> <button type="button" class="btn btn-danger">真實名稱</button> </div> <!-- /btn-group --> <input type="text" class="form-control" name="realName"> </div> </div> </div> <div class="row row-margin"> <div class="col-xs-8 col-xs-offset-1 tipinfo"> <div class="input-group"> <div class="input-group-btn"> <button type="button" class="btn btn-danger">所屬級別</button> </div> <!-- /btn-group --> <select class="form-control" name="partnerLevelId"> <option value="1">市級合伙人</option> <option value="2">生活館關注</option> <option value="3">VIP合伙人</option> </select> </div> </div> </div> <div class="row row-margin"> <div class="col-xs-8 col-xs-offset-1 tipinfo"> <div class="input-group"> <div class="input-group-btn"> <button type="button" class="btn btn-danger">上級合伙人</button> </div> <!-- /btn-group --> <select name="parentPartnerId" class="form-control"> <OPTION value="0">無</OPTION> <c:forEach items="${parentPartnerList}" var="parentPartner"> <option value="${parentPartner.partnerId}">${parentPartner.partnerName}</option> </c:forEach> </select> </div> </div> </div> <div class="row row-margin"> <div class="col-xs-8 col-xs-offset-1 tipinfo"> <div class="input-group"> <div class="input-group-btn"> <button type="button" class="btn btn-danger">投資金額</button> </div> <!-- /btn-group --> <input type="text" class="form-control" name="joinFee" placeholder="元"> </div> </div> </div> <div class="row row-margin"> <div class="col-xs-5 col-xs-offset-4"> <button type="button" class="btn btn-default " onClick="goback();">返回</button>    <button type="button" class="btn btn-primary btn-danger" id="submit1">提交</button> </div> </div> </div> </div> </div> </div> </form>
3.加載驗證器
在頁面加載完整之后,通過如下js代碼加載驗證器。
$(function() { $('#thisForm').formValidation({ message : 'This value is not valid', icon : { valid : 'glyphicon glyphicon-ok', invalid : 'glyphicon glyphicon-remove', validating : 'glyphicon glyphicon-refresh' }, fields : { partnerName : { message : '合伙人名稱驗證不通過', validators : { notEmpty : { message : '不能為空' }, /* * stringLength: { min: 6, max: 30, message: 'The username must * be more than 6 and less than 30 characters long' }, */ /* * remote: { url: 'remote.php', message: 'The username is not * available' }, */ /* * regexp: { regexp: /^[a-zA-Z0-9_\.]+$/, message: 'The username * can only consist of alphabetical, number, dot and underscore' } */ } }, realName : { validators : { notEmpty : { message : '不能為空' }, } }, phone : { validators : { notEmpty : { message : '不能為空' }, phone : { message : '不是有效的電話號碼', country:'CN' }, remote: { type: 'POST', url: 'partnerByPhone', message: '該號碼已經存在', // delay: 1000 } } }, joinFee: { validators: { notEmpty: { message:'不能為空' }, digits: { message:'不是有效的金額' }, greaterThan: { value: 0 }, } } } }) });
相信很容易就可以看懂上述驗證器的邏輯,就是一個封裝好的json對象,以表單的name作為鍵,對每一個表單規定驗證規則,以及驗證失敗后輸出的message。以上列出了幾種常見的驗證規則,如果想要更多驗證規則,可以從下載的文件中去找尋demo.
這里再列出一些比較有用的驗證規則,都是我從demo上面摘抄下來的。
--長度要求和正則表達式
username: { message: 'The username is not valid', validators: { notEmpty: { message: 'The username is required and can\'t 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' } } },
--email:
email: {
validators: {
notEmpty: {
message: 'The email address is required and can\'t be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
},
--電話
phone: {
validators: {
notEmpty: {
message: '不能為空'
},
phone:{
message: '不是合法電話',
country:'CN'
}
}
}
--網站
website: {
validators: {
uri: {
message: 'The input is not a valid URL'
}
}
}
--郵編
zipCode: {
validators: {
zipCode: {
country: 'CN',//中國郵編
message: 'The input is not a valid US zip code'
}
}
}
--密碼及確認
password: {
validators: {
notEmpty: {
message: 'The password is required and can\'t be empty'
}
}
},
confirmPassword: {
validators: {
notEmpty: {
message: 'The confirm password is required and can\'t be empty'
},
identical: {
field: 'password',
message: 'The password and its confirm are not the same'
}
}
},
--數字
age: {
validators: {
notEmpty: {},
digits: {},
greaterThan: {
value: 18
},
lessThan: {
value: 100
}
}
},
--整數
'limitPromotion.stock': { validators: { notEmpty: { message:'不能為空' }, regexp: { regexp: /^([0-9][0-9]*)$/, message: '必須為整數' } } },
--日期
'employee.birthday' : { message : '表單校驗失敗', validators : { notEmpty : { message : '不能為空' }, //日期格式 date: { format: 'YYYY-MM-DD hh:mm:ss', message : '不是合法的日期' } } },
--遠程調用
username: {
message: 'The username is not valid',
validators: {
notEmpty: {
message: 'The username is required and can\'t be empty'
},
remote: {
type: 'POST',
url: 'partnerByPhone',
message: '電話號碼已使用',
//delay: 1000
}
}
}
關於遠程調用就是需要去訪問服務端的接口,來驗證輸入的表單是否有效,經常出現的場景是我們需要驗證一個用戶名是否已經被注冊過了。該遠程調用返回的響應是一個json的數據,如果是{ “valid”: true }表示通過驗證,否則{ “valid”: false}表示驗證失敗。
其中服務端的代碼示例如下:
@ResponseBody @RequestMapping("partnerByPhone") public Map<String, Object> partnerByPhone(String phone) { TPartner partner = partnerService.getPartnerByPhone(phone); Map<String, Object> maps = new HashMap<String, Object>(); if (partner == null) { maps.put("valid", true); } else { maps.put("valid", false); } return maps; }
4.提交表單時候手動調用驗證
一般情況下,當我們提交表單的時候,需要手動調用驗證,可以用如下代碼來實現。針對上述表單。
$("#submit1").click(function() { var $form = $("#thisForm"); var bv = $form.data('formValidation'); bv.validate(); if(bv.isValid()){ $.ajax({ type:'post', url:'partnerSave', data:$('#thisForm').serialize(), dataType:'html', success:function(data){ if(data>0){ alert("成功"); location.href="partnerHome"; }else{ alert("失敗"); } } }); } });
怎么樣,就是這么簡單。我們來看看效果吧。當然提示錯誤的語言和一些標簽的樣式你可以自己去修改。


總的來說,這還是一款比較容易上手的驗證器,有需要的朋友可以嘗試一下。
