生活随笔
收集整理的這篇文章主要介紹了
jquery 表单验证插件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
其他:
<form action="">First name: <input type="text" name="FirstName" value="Bill" /><br />Last name: <input type="text" name="LastName" value="Gates" /><br />
secret: <input type="text" name="secret" value="Yousecret" /><br /></form>$("form").serialize(); //FirstName=Bill&LastName=Gates一般用法:$.ajax({type: 'post',url: 'your url',data: $("form").serialize(),success: function(data) {// your code}});
serializeArray()讀取form表單中的所有數據列表
var siginList = $('form').serializeArray();
<div contenteditable="true">我是一個可被編輯的DIV</div>
一.jqeuryvalidate
二.nice-validate
更多>>>
官方文檔
參數選項
$("form").validator({debug :0, //調試//0:關閉實時驗證,只在提交表單的時候執行驗證//1:輸入框失去焦點(focusout)時執行驗證//2:輸入框改變值(input)時執行驗證//3:輸入框失去焦點和改變值(綜合 1 + 2) (v0.8.0+)//8:同 2,并且詳細提示每個規則的結果 (v0.9.0+)//9:同 3,并且詳細提示每個規則的結果 (v0.9.0+)//大于 100 的數值:驗證延遲時間timely :1; //實時驗證theme :"default", //主題stopOnError :false, //在第一次錯誤時停止驗證 關閉此開關,以便一次性顯示所有消息focusInvalid :true, //第一個錯誤字段自動獲得焦點focusCleanup :false, //輸入框獲得焦點時清除驗證消息ignoreBlank :false, //不驗證空值的字段(只針對實時驗證)ignore :"", // 默認忽略驗證 jQuery 選擇器選中的字段ignore :':hidden', //任何不可見的元素,都不作驗證ignore :'#tab2', //id為tab2下的所有子元素都不作驗證display:'null', // 自定義消息中{0}的替換字符display:Function(elem){ // 自定義消息中{0}的替換字符return $(elem).closest('.form-item').children('label:eq(0)').text();},target :null, //默認 自定義消息的顯示位置target :'#myContainer', // 將所有消息全部提示在 id 為 myContainer 里面target:Function(elem){// 自己指定消息容器位置var $formitem = $(elem).closest('.form-item'),$msgbox = $formitem.find('span.msg-box');if (!$msgbox.length) {$msgbox = $('<span class="msg-box"></span>').appendTo($formitem);}return $msgbox;},valid:null,// 默認 表單驗證通過時調用此函數invalid: function(form){//表單驗證通過時調用此函數// 表單驗證通過,提交表單$.post(url, $(form).serialize() ).done(function(d){// some code});},invalid:null,//表單驗證失敗后的回調。也可以使用 invalid.form 事件invalid:function(){//$('#form').on('invalid.form', function(e, form, errors){});},validation:null,//驗證每個字段后調用此函數validation: function(element, result){$("#submitBtn").prop('disabled', !element.form.isValid)},rules:null,//自定義規則rules: {//自定義用于當前實例的規則,支持兩種定義方式// 自定義驗證函數,具有最大的靈活性myRule: function(el, param, field){//驗證并返回布爾值},// 簡單配置正則及錯誤消息another: [/^\w*$/, 'Please enter the letters or underscore.']},messages:null,//自定義消息messages: {required: "不能為空",email: "請填寫正確的郵件地址",myRule:"自定義規則的提示消息"},fields:null,//配置字段規則及參數fields: {//為input[name=foo]調用前面定義的兩個規則foo: 'required; myRule[param]; another',username: {//字段規則rule: "姓名: required; myRule; rule2; rule3",//(自定義字段中?)每個規則的錯誤消息msg: {myRule:"自定義規則的提示消息", #注意這里值為false和""則會顯示默認的錯誤提示required: "請填寫姓名",rule2: "xxxx",rule3: "xxxx"},//自定義獲得焦點時的友好提示信息tip: "填寫真實姓名有助于朋友找到你",//自定義字段驗證成功后顯示的消息ok: "{0}填寫正確", //返回姓名填寫正確//是否啟用實時驗證,默認繼承timely: false,//驗證當前字段,但是實際上在 target 的元素上提示錯誤消息//如果目標元素是輸入框(input,textarea、select),將會以目標元素為基準點,插入一條消息;//如果目標元素是消息占位(className 為 msg-box),這和直接使用消息占位沒有區別//其他情況下,直接顯示在target指向的容器中target: "#msg_holder",//字段驗證通過的回調valid:function(form){},//字段驗證失敗的回調valid:function(form){},//使用 dataFilter 回調可以轉換 ajax 返回的結果為 nice-validator 支持的格式dataFilter:function(form){},must:true,//是否強制驗證該字段msgWrapper:"span",//自定義該字段的消息容器的標簽名msgMaker:"",//自定義該字段的消息生成器 參數?msgClass:"",//自定義該字段的消息Class 在.msg-box消息容器標簽上msgStyle:"font-size:14px;",//自定義該字段的消息 CSS 樣式 綁定在.msg-box消息容器標簽上getValue:function(){},//自定義 value 的 getter 參數?setValue:function(){},//自定義 value 的 setter 參數?},},beforeSubmit :null,//在提交表單之前調用此函數beforeSubmit:function(form){//一般在提交之前修改某些form元素},dataFilter:null,//轉換服務端通過ajax返回的數據為插件支持的格式一般和remote默認規則搭配使用dataFilter:function(data){//假設服務端返回結果為: {"status":600, "msg":"名字已被占用"}if (data.status === 200) return "";else return data.msg;},//主題相關的參數showOk:true,//默認 是否顯示成功提示(前提是有傳ok的消息) 返回布爾 或者字符串showOk:false,//如果設置成false在字段驗證通過后將只是簡單的隱藏消息。showOk:'正確',//如果傳遞一個字符串,在驗證通過后將提示這個消息showOk:'',//如果設置成空字符串,將只顯示一個成功的圖標validClass:'has-succes', //為驗證通過的form表單添加的class名invalidClass:"has-error",//驗證不通過的輸入框添加的class名bindClassTo:"#verifiable",//設置 validClass 和 invalidClass 添加到的位置formClass:"n-default", //主題的 class 名稱,添加在 form 上msgClass: "n-top", //消息將自動顯示在輸入框上邊msgClass: "n-right", //默認 消息將自動顯示在輸入框右邊msgClass: "n-bottom", //消息將自動顯示在輸入框下邊msgClass: "n-left", //消息將自動顯示在輸入框左邊msgClass: "n-right myclass", //消息將自動顯示在輸入框右邊,你還可以通過myclass來定義更多樣式msgStyle:"margin-left:-10px; margin-top:10px;",//為消息容器 自定義cssmsgWrapper:"span",//消息容器的元素標簽msgMaker:null,//自定義消息 HTML 結構 為false則不生成提示消息msgMaker: function(opt){return '<span class="'+ opt.type +'">' + opt.msg + '</span>';/* opt包含的子屬性
? ? ? ? ? type:消息類型(可能的值為:error / ok / tip / loading)
? ? ? ? ? cls: 即msgClass參數的值
? ? ? ? ? style: 即msgStyle參數的值
? ? ? ? ? icon: 即msgIcon參數的值
? ? ? ? ? arrow: 即msgArrow參數的值
? ? ? ? ? show: 即msgShow參數的值
? ? ? ? ? hide: 即msgHide參數的值
以上 msgMaker 配置,將生成如下消息結構<div class="msg-box n-right" for="user[name]"><span class="n-error">Please fill this field.</span></div>*/},msgIcon:"<span class="n-icon"></span>",//自定義消息圖標的 HTML 模板msgArrow:"", //自定義消息箭頭的 HTML 模板msgShow:null, //消息提示之前調用此函數msgShow:function($msgbox, type){//},msgHide:null,//消息隱藏之前調用此函數msgHide:function($msgbox, type){//}});
消息體html結構:
<span class="msg-box" for="quanxian" style=""><span role="alert" class="msg-wrap n-error"><span class="n-icon"></span><span class="n-msg">協議必選</span></span></span>
事件:
.on("validation"):描述:每次驗證完一個字段,都會觸發?validation?事件,通過該事件可以獲取到當前驗證字段的驗證結果。
$('#form').on('validation', function(e, current){var form = this;// form 中是否所有字段都驗證通過console.log(form.isValid);// 當前驗證字段是否通過console.log(current.isValid);// 打印其他屬性console.log(current.element);console.log(current.value);console.log(current.msg);});
.on("valid.form"):在表單驗證通過后觸發
$('#form').on('valid.form', function(e, form){//do something...});
.on("invalid.form"):在表單驗證不通過后觸發
$('#form').on('invalid.form', function(e, form, errors){//do something...});
.on("valid.field"):在字段驗證通過后觸發
$('#username').on('valid.field', function(e, result){//do something...});
.on("invalid.field"):在字段驗證不通過后觸發
$('#username').on('invalid.field', function(e, result){//do something...});
.on("valid.rule"):在規則驗證通過后觸發
$('#username').on('valid.rule', function(e, ruleName){if (ruleName === 'remote') {//do something...}});
.on("invalid.rule"):在規則驗證不通過后觸發
$('#username').on('invalid.rule', function(e, ruleName){if (ruleName === 'remote') {//do something...}});
發布:
.trigger("validate"):手動觸發字段執行驗證
觸發類型//①$input.trigger("validate"); 手動觸發元素進行驗證//如:手動調用username字段驗證$('input[name="username"]').trigger("validate");//②$form.trigger("validate"); v0.7.0+ 手動觸發表單進行驗證,驗證通過后不會自動提交//如:手動調用表單驗證$('#form').trigger("validate");//③$form.trigger("submit"); 手動觸發表單提交,在提交前會自動驗證//如:手動調用表單提交$('#form').trigger("submit");//④$input.trigger("showtip"); v0.5.0+ 觸發元素顯示tip消息//手動調用驗證初始化完成后,立即顯示所有字段的提示$('#form').validator().trigger("showtip");
.trigger("showmsg", [type, message]):觸發字段提示消息
// 手動調用字段驗證成功消息$("#username").trigger("showmsg", ["ok", "Great name"]);// 手動調用input字段驗證錯誤消息$("#username").trigger("showmsg", ["error", "Name is already taken"]);// 手動調用(input聚焦選中)友好的提示消息$("#username").trigger("showmsg", ["tip", "Others make a good name for you impressed"]);// 手動調用已經綁定的提示消息 (data-tip)$("#username").trigger("showmsg", ["tip"]);// 手動調用所有提示消息$("#form").trigger("showmsg", ["tip"]);
.trigger("hidemsg"):觸發字段隱藏消息
// 手動調用隱藏指定字段的消息$("#username").trigger("hidemsg");// 手動調用隱藏整個表單的提示消息$("#form").trigger("hidemsg");
插件方法:
$('#form1').validator({選項參數})? ? ? : 根據參數初始化驗證,驗證 jQuery 選中的表單
$('#form1').validator(function(){})? ? : 初始化驗證,驗證 jQuery 選中的表單,驗證通過后執行回調
// 等同于 $('#form1').validator({ valid: function(){}, });
$('#form1').validator(instanceMethod, arg1, arg2...?)? ? :通過.validator()?方法調用實例方法?
// 清空表單驗證消息$('#form1').validator("cleanUp");// 銷毀表單驗證$('#form1').validator("destroy");
$('#form1').isValid( callback )?判斷某個區域或者某個字段是否驗證通過,如果字段中有異步 ajax 驗證,需要通過 callback 獲取驗證結果
// 使用回調函數獲取驗證結果$('#mobile').isValid(function(v){if (v) {// do something}});// v0.10.5+ 還支持下面這種寫法,即回調不帶參數,就是驗證通過的回調$('#mobile').isValid(function(){// do something});// 如果驗證的字段中沒有 ajax 異步驗證,直接獲取結果也是可以的if ( $('#mobile').isValid() ) {// do something}
靜態方法
$.validator(selector, options)
// 即使 "#form1" 這個表單被動態加載,也可以驗證$.validator("#form1", {timely: 2,stopOnError: true,fields: {email: "required;email",password: "required;length(6~16)",mobile: "required;mobile"}});
$.validator.config(options):配置全局選項? ?建議配置在 local 配置文件(如:zh-CN.js)中
$.validator.config({timely: 2});
$.validator.config(rules: {mobile: [/^1[3-9]\d{9}$/, "請填寫有效的手機號"],chinese: [/^[\u0391-\uFFE5]+$/, "請填寫中文字符"]});
$.validator.setTheme(name, options):配置全局主題? ? 參考配置選項
$.validator.setTheme("myTheme", {formClass: "nice-flat",msgClass: "n-right",timely: 2,stopOnError: true});
instance (實例方法)
.test(elem, rule):驗證字段是否符合指定的規則 返回布爾
$("#myForm").validator({rules: {loginName: function(element) {return /^[a-zA-Z]\w{3,}/.test(element.value)|| this.test(element, "mobile")|| this.test(element, "email")|| 'Please fill user name, phone number or E-mail';}},fields: {username: "required; loginName",password: "required; length(6~16)"}});
.setField(key, field):動態配置字段參數
$('form').validator("setField", "username", "required;");// Remove the field's verification.$('form').validator("setField", "username", null);
.setField(obj):動態配置字段參數
$('form').validator("setField", {username: "required;username",pwd: "required;password"});
.showMsg(elem, obj):使字段提示消息(不推薦),推薦使用.trigger("showmsg")
.hideMsg(elem):使字段隱藏消息(不推薦),推薦使用.trigger("hidemsg")
.holdSubmit(hold):防止表單重復提交的措施
$("#myForm").validator({valid: function(form){var me = this;// Before submitting the form, hold form, to prevent duplicate submission.me.holdSubmit();$.ajax({url: "xxx.php",data: $(form).serialize(),type: "POST",success: function(){// After the form is submitted successfully, release hold.me.holdSubmit(false);}});}});
.cleanUp():清除表單中的全部驗證消息
$('#form1').validator('cleanUp');
.destroy():銷毀表單驗證實例
$('#form1').validator('destroy');
內置規則:
required - 使字段必填?適用于 input、textarea、select(注意 :":filled" 是一個jquey的選擇器擴展,匹配填充值了的表單元素,用法和:checked、:radio、:checkbox一致)
①required②required("input:filled" )、required(#id:checked)、required(#id:enabled)、...③required(ruleName) 滿足規則(某個默認規則自定義規則) ruleName 則字段必填④required(from, class, count) :className 為 contact 的字段至少填寫一個eg:<input class="contact" name="mobile" placeholder="手機號"data-rule="required(from, .contact); mobile"data-msg-required="請至少填寫一種聯系方式"><input class="contact" name="tel" placeholder="電話"data-rule="required(from, .contact); tel"><input class="contact" name="email" placeholder="郵箱"data-rule="required(from, .contact); email">⑤required(not, value) 必填但排除value
checked - 必選,還可以控制選擇項目的數量
規則 描述checked 必選checked(n) 必選 n 項checked(n~) 至少選擇 n 項checked(~n) 最多選擇 n 項checked(n1~n2) 選擇 n1 到 n2 項
match - 當前字段與另一個字段比較
規則 描述match(name) 當前字段值必須和 name 字段的值匹配match(eq, name) 同上match(neq, name) 當前字段值必須和 name 字段值不同match(lt, name) 當前字段值必須小于 name 字段值match(gt, name) 當前字段值必須大于 name 字段值match(lte, name) 當前字段值必須小于等于 name 字段值match(gte, name) 當前字段值必須大于等于 name 字段值match(gte, name, date) 當前日期值必須大 于等于 name 字段日期值match(gte, name, datetime) 當前時間值必須大于等于 name 字段時間值
remote - 獲取服務器端驗證的結果
remote(url)remote(get:URL) 默認postremote(cors:post:/user/checkName) 強制跨域<input type="text" name="username"data-rule="required;remote({:U('User/test')})">然后經過user控制器test方法處理后返回返回是字符串:返回" ":通過; 不為空 則 將作為錯誤信息輸出返回json時:// 驗證通過{"ok": "名字很棒"} //$msg['ok']="名字很棒";echo json_encode($msg);// 驗證不通過{"error": "名字已被占用"} //$msg['error']="名字已被占用";echo json_encode($msg);// 結果在第二級 data{"status": 200, "data": {"error": "名字已被占用"}}
integer - 只能填寫整數
規則 描述integer 整數integer(+) 正整數integer(+0) 正整數和零integer(-) 負整數integer(-0) 負整數和零
range - 只能填寫指定范圍的數
規則 描述range(n~) 請填寫不小于 n 的數range(~n) 請填寫不大于 n 的數range(n1~n2) 請填寫 n1 到 n2 的數range(n1~n2, false) 請填寫 n1 到 n2 的數(不包含邊界值)(v0.9.0+)
length - 字段值必須符合指定長度
規則 描述length(n) 請填寫 n 個字符length(n~) 請至少填寫 n 個字符length(~n) 請最多填寫 n 個字符length(n1~n2) 請填寫 n1 到 n2 個字符length(n~, true) 請至少填寫 n 個字符(全角字符計算雙字符)
filter - 過濾當前字段的值,不做驗證
規則 描述filter 過濾 <>`"' 和字符實體編碼的字符filter(RegExp) 自定義過濾正則
驗證方式:
例1. DOM傳參? ??DOM 綁定規則,無需 JS 代碼
1. 要驗證一個表單,只需要給字段綁定規則“data-rule”就可以了2. 字段可以有多條規則,規則之間用分號(;)分隔3. js初始化不是必要的,只要是字段并且帶有“data-rule”屬性,即使是新插入的一段DOM也可以立馬驗證4. 其中:required是內置規則(核心自帶),username、password是配置文件中設置的全局規則(配置文件)<form id="demo_11" action="results.php" method="post" autocomplete="off"><fieldset><p><input name="user[name]" data-rule="required;username" placeholder="用戶名"></p><p><input name="user[pwd]" data-rule="required;password" placeholder="密碼"></p></fieldset><button type="submit">提交</button></form><input type="text" name="username" data-rule="required;"> :提示 此處不能為空<input type="text" name="username" data-rule="用戶名:required;"> :提示 用戶名不能為空<input type="text" name="username"data-rule="required;"data-tip="輸入你的名字與姓氏。" 可選:聚焦提示data-ok="名字很棒。" 可選:默認為一個綠色的勾data-msg-required="全名必填!" 可選:data-msg-指定的規則 默認錯誤只顯示紅色的X>
例2. js傳參(這和上面的DOM傳參等價)??JS 配置規則,無侵入 DOM
HTML<form id="demo_12" action="results.php" method="post" autocomplete="off"><fieldset><p><input name="user[name]" placeholder="用戶名"></p><p><input name="user[pwd]" placeholder="密碼"></p></fieldset><!--button type="submit">提交</button--><a href="javascript:" class="submit-btn">提交</a></form>Javascript$('#demo_12').validator({fields: {'user[name]': 'required; username;','user[pwd]': 'required; password;'}})// 使用鏈接代替submit按鈕(注意:這種情況下輸入框里面的回車鍵不能觸發submit事件)$("#xxoo").on("click", "a.submit-btn", function(e){$(e.delegateTarget).trigger("submit");});
例3. radio的必選
1. 對于checkbox和radio,要“必填”的話,不能使用“required”,而是使用“checked”2. 你只需要在第一個checkbox或者radio上面綁定規則就可以了3. 消息會自動生成,并且顯示在最后面,你無需關注消息怎么顯示<form id="demo_51" action="results.php" method="post" autocomplete="off"><fieldset><label class="form-label">性別:</label><label><input type="radio" name="gender" value="1" data-rule="checked">男</label><label><input type="radio" name="gender" value="2">女</label><label><input type="radio" name="gender" value="0">保密</label></fieldset><div class="form-submit"><button type="submit">提交</button></div></form><form id="demo_52" action="results.php" method="post" autocomplete="off"><fieldset><label class="form-label">興趣:</label><label><input type="checkbox" name="interest[]" value="0" data-rule="checked">看書</label><label><input type="checkbox" name="interest[]" value="1">上網</label><label><input type="checkbox" name="interest[]" value="2">睡覺</label><label><input type="checkbox" name="interest[]" value="3">運動</label><label><input type="checkbox" name="interest[]" value="4">發呆</label></fieldset><div class="form-submit"><button type="submit">提交</button></div></form>
控制選中項目數
1.?checked[2~]表示選擇的項目要在2項以上
2. 不要對:radio使用參數,因為本身就是單選,直接checked就可以了
<form?id="demo_53"?action="results.php"?method="post"?autocomplete="off">
<fieldset>
<label?class="form-label">興趣:</label>
<label><input?type="checkbox"?name="interest[]"?value="0"?data-rule="checked[2~]">看書</label>
<label><input?type="checkbox"?name="interest[]"?value="1">上網</label>
<label><input?type="checkbox"?name="interest[]"?value="2">睡覺</label>
<label><input?type="checkbox"?name="interest[]"?value="3">運動</label>
<label><input?type="checkbox"?name="interest[]"?value="4">發呆</label>
</fieldset>
<div?class="form-submit">
<button?type="submit">提交</button>
</div>
</form>
例4. Ajax提交表單
1. 可以通過valid參數傳入回調,參見配置
2. 也可以直接接收valid.form事件(下面例子采用接收事件的方式),參見事件
HTML<div id="result_14" class="tip-ok" style="display:none">提交成功</div><form id="demo_14" autocomplete="off"data-validator-option="{theme:'simple_right'}"><fieldset><p><input name="username" data-rule="用戶名:required;username" placeholder="用戶名"></p><p><input name="password" data-rule="密碼:required;password" placeholder="密碼"></p></fieldset><button type="submit">提交</button></form>Javascript//接收表單驗證通過的事件$('#demo_14').bind('valid.form', function(){$.ajax({url: 'results.php',type: 'POST',data: $(this).serialize(),success: function(d){$('#result_14').fadeIn(300).delay(2000).fadeOut(500);}});});
自定義規則:
注意:自定義規則如果與內置規則同名,則自定義規則優先
通過 DOM 方式自定義規則(只對當前字段有效)
<input name="demo" data-rule="required; xxx" data-rule-xxx="[/^\d{6}$/, '請輸入6位數字']">
通過?rules?配置規則(當前表單實例有效)
<input name="demo">$('#form1').validator({rules: {// 使用正則表達式定義規則mobile: [/^1[3-9]\d{9}$/, "請填寫有效的手機號"],// 使用函數定義規則xxx: function(elem, param) {return /^1[3458]\d{9}$/.test($(elem).val()) || '請檢查手機號格式';}},fields: {// 對字段 username 應用規則 mobile'username': 'required;mobile'}});
全局規則:
提交方式:
提交方式1:表單驗證通過后自動原生方式提交
<form id="form1" action="register.php"><label>Email</label><input type="email" name="email" data-rule="required;email"><label>Password</label><input type="password" name="pwd" data-rule="required;length(6~16)"><button type="submit">提交</button></form>
提交方式2:js使用驗證通過回調
$('#form1').validator({valid: function(form) {// do something// use native submit.form.submit();}});
提交方式3:綁定表單驗證通過的事件(參考:valid.form事件)
$('#form1').on('valid.form', function(e){// You can do something, then submit form by native// this.submit();// or use ajax submit$.post("path/to/server", $(this).serialize()).done(function(d){// some code});});
總結
以上是生活随笔為你收集整理的jquery 表单验证插件的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。