使用FormValidation進行表單驗證
一、概述 1.最好的jquery表單驗證外掛 2.最新下載:(收費) http://formvalidation.io/ http://formvalidation.io/download/ 3.官網案例: http://formvalidation.io/examples/ 4.指南: http://formvalidation.io/getting-started/ (api)http://formvalidation.io/api/ (引數)http://formvalidation.io/settings/ (驗證器列表)http://formvalidation.io/validators/ 5.引入: <link href="css/bootstrap.min.css" rel="stylesheet" > <link href="css/formValidation.min.css" rel="stylesheet" >
<script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/formValidation.min.js"></script> <script type="text/javascript" src="js/framework/bootstrap.min.js"></script> <script type="text/javascript" src="js/zh_CN.js"></script> <script type="text/javascript"> 6.不要為提交按鈕使用name =“submit”或id =“submit”屬性。否則,表單無法在驗證後提交 二、使用 1.基礎案例: $("#defaultForm").formValidation({ fields:{ username:{//username為表單元素的name屬性值 message:"使用者名稱輸入錯誤", validators:{ notEmpty:{ message:"使用者名稱不能為空" }, stringLength:{ min:3, max:6, message:"使用者名稱長度必須在3到6之間" }, regexp:{ regexp:/^[a-zA-Z0-9_]+$/, message:"使用者名稱中有非法字元" } } } } }); 2.新增圖示:根據欄位有效性指示有效/無效/驗證圖示。 $("#defaultForm").formValidation({ icon: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields:{ username:{ message:"使用者名稱輸入錯誤", validators:{ notEmpty:{ message:"使用者名稱不能為空" } } } } }); 3.遠端驗證器 1)遠端驗證時候,remote驗證器自動附加當前驗證欄位的資料給伺服器 remote: { message: '使用者名稱已存在!', url: '/FormValidation_demo/CheckUsernameServlet',//url不存在時候,返回false type: 'POST' } 2)遠端URL必須返回包含valid的JSON物件或json串 { "valid": true } 表示驗證可用 或 { "valid": false } 3)如果遠端URL響應{"valid":null},則驗證器將被忽略 4.自定義驗證規則:使用callback驗證器 要求輸入安全密碼,必須滿足以下所有條件:
長度必須超過8個字元 必須包含至少一個大寫字母 必須包含至少一個小寫字母 必須至少包含一位數字 password:{ validators:{ notEmpty:{ message:"密碼不能為空" }, callback:{ message:"密碼輸入錯誤", callback:function(value,validator,$field){ if(value === ''){ return true; } if(value.length < 8){ return { valid:false, message:"密碼長度不能小於8位" }; } // The password doesn't contain any uppercase character if (value === value.toLowerCase()) { return { valid: false, message: '密碼至少包含一個大寫字母' } }
// The password doesn't contain any uppercase character if (value === value.toUpperCase()) { return { valid: false, message: '密碼至少包含一個小寫字母' } }
// The password doesn't contain any digit if (value.search(/[0-9]/) < 0) { return { valid: false, message: '它必須至少包含一個數字' } } return true; } } } 5.常用驗證器 1)email驗證器: validators:{ emailAddress:{ message:"email格式錯誤" } } 2)between驗證器:檢查輸入值是否在兩個給定數字之間 validators:{ between:{ min:0, max:150, message:"年齡輸入錯誤" } } 3)different驗證器:如果輸入值與給定欄位的值不同,則返回true different:{ field:"username", message:"密碼不能與使用者名稱相同" } 4)numeric驗證器:檢查值是否是數字 validators:{ numeric:{ message:"數量必須為數字" } } 5)integer驗證器:驗證整數。接受正數和負數 validators:{ integer:{ message:"數量必須為整數" } } 6)日期驗證器: date:{ format:"yyyy-mm-dd", min: } 6.%s表示動態訊息,與特定驗證器相關,與引數定義先後無關 age:{ validators:{ between:{ min:0, max:150, message:"年齡必須在%s和%s之間" } } } 7.verbose: false//當有一個驗證器驗證失敗時,設定將停止驗證 8.計算驗證碼: 1)// Generate a simple captcha function randomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); }; $('#captchaOperation').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' ')); 2)<div class="form-group"> <label class="col-sm-3 control-label" id="captchaOperation"></label> <div class="col-sm-2"> <input type="text" class="form-control" name="captcha" /> </div> </div> 3)captcha:{ validators:{ callback:{ message:"驗證碼輸入錯誤", callback:function(value, validator, $field){ var items = $("#captchaOperation").html().split(' '); var sum = parseInt(items[0])+parseInt(items[2]); return value==sum; } } } } 9.selector:它被用於不能使用name該欄位的屬性的情況 如表單元素名為"emp.ename",直接在fields中像下面這樣寫報錯: fields:{ emp.ename:{ validators:{ notEmpty:{ message:"姓名不能為空" } } } } 這是應該給該表單新增一個id,如<input type="text" name="emp.ename" id="ename"> 然後驗證改為: fields:{ ename:{ selector:"#ename",//指定要驗證的表單元素 validators:{ notEmpty:{ message:"姓名不能為空" } } } } 10.把錯誤訊息顯示在設定的指定位置上 <div class="form-group"> <label class="col-md-3 control-label" >birthday</label> <div class="input-group date col-md-5" id="birthday"> <input type="text" class="form-control" name="birthday" readonly/> <span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span> <span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span> </div> <div class="col-md-3 col-md-offset-3" id="msg"></div> </div> birthday:{ validators:{ notEmpty: { message: '生日不能為空' } } } err:{ container: function($field, validator) { if($field.attr("name") == "birthday"){ return $("#msg");//返回特定jquery物件 } return null;//返回null,為預設值 } } 11.把上面的頁面修改為如下所示,錯誤提示會顯示在預設位置,就不用指定新的錯誤位置了 <div class="form-group"> <label class="col-md-3 control-label" >birthday</label> <!-- 多個這層div --> <div class="col-md-5"> <div class="input-group date" id="birthday"> <input type="text" class="form-control" name="birthday" readonly/> <span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span> <span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span> </div> </div> </div> 12.修改提示圖示預設位置 <style type="text/css"> /** * Override feedback icon position * See http://formvalidation.io/examples/adjusting-feedback-icon-position/ */ #defaultForm .form-control-feedback { top: 0; right: -15px; } </style> 把#defaultForm改為具體div的id,可以只修改某個驗證圖示位置 13.與Bootstrap DateTimePicker 一起使用的時候,在選擇時間後不會馬上驗證,要等到表單提交才驗證 可編寫如下程式碼,改為立即驗證: $("#birthday").datetimepicker({ format:'yyyy-mm-dd', language:'zh-CN', minView:'month', autoclose:true }).on("changeDate",function(){ //在修改日期後,對name為birthday的表單元素進行重新驗證 $('#defaultForm').formValidation('revalidateField', 'birthday'); }); 14.完整案例 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link href="css/bootstrap.min.css" rel="stylesheet" > <link href="css/formValidation.min.css" rel="stylesheet" > <link href="css/bootstrap-datetimepicker.min.css" rel="stylesheet" >
<script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/formValidation.min.js"></script> <script type="text/javascript" src="js/framework/bootstrap.min.js"></script> <script type="text/javascript" src="js/zh_CN.js"></script> <script type="text/javascript" src="js/bootstrap-datetimepicker.min.js"></script> <script type="text/javascript" src="js/bootstrap-datetimepicker.zh-CN.js"></script> <script type="text/javascript"> $(function(){ $("#birthday").datetimepicker({ format:'yyyy-mm-dd', language:'zh-CN', minView:'month', autoclose:true }).on("changeDate",function(){ $('#defaultForm').formValidation('revalidateField', 'birthday'); }); // Generate a simple captcha function randomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); }; $('#captchaOperation').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' '));
$("#defaultForm").formValidation({ message:"值輸入錯誤", icon: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields:{ firstName:{ row: '.col-md-4', validators:{ notEmpty:{ message:"firstName不能為空" } } }, lastName:{ validators:{ notEmpty:{ message:"lastName不能為空" } } }, username:{ verbose: false,//當有一個驗證器驗證失敗時,設定將停止驗證。 validators:{ notEmpty:{ message:"使用者名稱不能為空" }, stringLength:{ min:3, max:6, message:"使用者名稱長度必須在3到6之間" }, regexp:{ regexp:/^[a-zA-Z0-9_]+$/, message:"使用者名稱中有非法字元" }, remote: { message: '使用者名稱已存在!', url: '/FormValidation_demo/CheckUsernameServlet',//url不存在時候,返回false type: 'POST' } } }, email:{ validators:{ emailAddress:{ message:"email格式錯誤" } } }, age:{ validators:{ between:{ max:150, min:0, message:"年齡必須在%s和%s之間" } } }, hobbyNumber:{ validators:{ integer:{ message:"數量必須為整數" } } }, password:{ validators:{ notEmpty:{ message:"密碼不能為空" }, different:{ field:"username", message:"密碼不能與使用者名稱相同" }, callback:{ message:"密碼輸入錯誤", callback:function(value,validator,$field){ if(value === ''){ return true; } if(value.length < 8){ return { valid:false, message:"密碼長度不能小於8位" }; } // The password doesn't contain any uppercase character if (value === value.toLowerCase()) { return { valid: false, message: '密碼至少包含一個大寫字母' } }
// The password doesn't contain any uppercase character if (value === value.toUpperCase()) { return { valid: false, message: '密碼至少包含一個小寫字母' } }
// The password doesn't contain any digit if (value.search(/[0-9]/) < 0) { return { valid: false, message: '它必須至少包含一個數字' } } return true; } } } }, captcha:{ validators:{ callback:{ message:"驗證碼輸入錯誤", callback:function(value, validator, $field){ var items = $("#captchaOperation").html().split(' '); var sum = parseInt(items[0])+parseInt(items[2]); return value==sum; } } } }, gender:{ validators:{ notEmpty:{ message:"性別沒有選擇" } } }, agree: { validators: { notEmpty: { message: '你必須同意我們的規定' } } }, birthday:{ validators:{ notEmpty: { message: '生日不能為空' }, callback:{ callback:function(value){ if(value == "2017-04-24"){ return { valid:false, message:"生日錯誤" }; } return true; } } } } } }); });
</script>
<style type="text/css"> /** * Override feedback icon position * See http://formvalidation.io/examples/adjusting-feedback-icon-position/ */ #defaultForm .form-control-feedback { top: 0; right: -15px; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="page-header"> <h2>Bootstrap Form</h2> </div>
<form id="defaultForm" method="post" class="form-horizontal" action="target.php"> <div class="form-group"> <label class="col-md-3 control-label">Full name</label> <div class="col-md-4"> <input type="text" class="form-control" name="firstName" placeholder="First name" /> </div> <div class="col-md-4"> <input type="text" class="form-control" name="lastName" placeholder="Last name" /> </div> </div>
<div class="form-group"> <label class="col-md-3 control-label">Username</label> <div class="col-md-5"> <input type="text" class="form-control" name="username" /> </div> </div>
<div class="form-group"> <label class="col-md-3 control-label">Email address</label> <div class="col-md-5"> <input type="text" class="form-control" name="email" /> </div> </div>
<div class="form-group"> <label class="col-md-3 control-label">Password</label> <div class="col-md-5"> <input type="password" class="form-control" name="password" /> </div> </div> <div class="form-group"> <label class="col-md-3 control-label" >birthday</label> <div class="col-md-5"> <div class="input-group date" id="birthday"> <input type="text" class="form-control" name="birthday" readonly/> <span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span> <span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span> </div> </div> <!-- 修改預設位置時候可用 <div class="col-md-3 col-md-offset-3"><span id="msg"></span></div> --> </div> <div class="form-group"> <label class="col-md-3 control-label">age</label> <div class="col-md-5"> <input type="text" class="form-control" name="age" /> </div> </div> <div class="form-group"> <label class="col-md-3 control-label">hobby number</label> <div class="col-md-5"> <input type="text" class="form-control" name="hobbyNumber" /> </div> </div>
<div class="form-group"> <label class="col-md-3 control-label">Gender</label> <div class="col-md-6"> <div class="radio"> <label> <input type="radio" name="gender" value="male" /> Male </label> </div> <div class="radio"> <label> <input type="radio" name="gender" value="female" /> Female </label> </div> <div class="radio"> <label> <input type="radio" name="gender" value="other" /> Other </label> </div> </div> </div>
<div class="form-group"> <label class="col-md-3 control-label" id="captchaOperation"></label> <div class="col-md-2"> <input type="text" class="form-control" name="captcha" /> </div> </div>
<div class="form-group"> <div class="col-md-6 col-md-offset-3"> <div class="checkbox"> <label> <input type="checkbox" name="agree" value="agree" /> Agree with the terms and conditions </label> </div> </div> </div>
<div class="form-group"> <div class="col-md-9 col-md-offset-3"> <button type="submit" class="btn btn-primary" name="signup" value="Sign up">Submit</button> </div> </div> </form> </div> </div> </div> </body> </html>
原始碼地址:
原始碼目錄結構: 1.FormValidation.zip:原始碼 2.FormValidation_demo:我的演示程式碼