Home > Web Front-end > JS Tutorial > body text

In-depth study of jQuery Validate form validation_jquery

WBOY
Release: 2016-05-16 15:24:46
Original
1308 people have browsed it

之前一篇文章介紹了jQuery Validate表單驗證入門的基礎知識,詳細內容請參閱《jQuery Validate表單驗證入門學習》今天這篇文章深入學習jQuery Validate表單驗證,以下是文章的全部內容:

1、用其他方式取代預設的 SUBMIT

$().ready(function() {
 $("#signupForm").validate({
    submitHandler:function(form){
      alert("submitted");  
      form.submit();
    }  
  });
});
Copy after login

使用 ajax 方式

 $(".selector").validate({   
 submitHandler: function(form) 
  {   
   $(form).ajaxSubmit();   
  } 
 }) 
Copy after login

可以設定 validate 的預設值,寫法如下:

 $.validator.setDefaults({
 submitHandler: function(form) { alert("submitted!");form.submit(); }
});
Copy after login

如果想提交表單, 需要使用 form.submit(),而不要使用 $(form).submit()。
2、debug,只驗證不提交表單
如果這個參數是true,那麼表單就不會提交,只進行檢查,調試時十分方便。

$().ready(function() {
 $("#signupForm").validate({
    debug:true
  });
});
Copy after login

如果一個頁面中有多個表單都想設定成為 debug,則使用:

$.validator.setDefaults({
  debug: true
})
Copy after login

3、ignore:忽略某些元素不驗證
ignore: ".ignore"
4、更改錯誤訊息顯示的位置
errorPlacement:Callback
指明錯誤放置的位置,預設情況是:error.appendTo(element.parent());即把錯誤訊息放在驗證的元素後面。

errorPlacement: function(error, element) { 
  error.appendTo(element.parent()); 
}
Copy after login

實例

<tr>
  <td class="label"><label id="lfirstname" for="firstname">First Name</label></td>
  <td class="field"><input id="firstname" name="firstname" type="text" value="" maxlength="100" /></td>
  <td class="status"></td>
</tr>
<tr>
  <td style="padding-right: 5px;">
    <input id="dateformat_eu" name="dateformat" type="radio" value="0" />
    <label id="ldateformat_eu" for="dateformat_eu">14/02/07</label>
  </td>
  <td style="padding-left: 5px;">
    <input id="dateformat_am" name="dateformat" type="radio" value="1" />
    <label id="ldateformat_am" for="dateformat_am">02/14/07</label>
  </td>
  <td></td>
</tr>
<tr>
  <td class="label"> </td>
  <td class="field" colspan="2">
    <div id="termswrap">
      <input id="terms" type="checkbox" name="terms" />
      <label id="lterms" for="terms">I have read and accept the Terms of Use.</label>
    </div>
  </td>
</tr>

errorPlacement: function(error, element) {
  if ( element.is(":radio") )
    error.appendTo( element.parent().next().next() );
  else if ( element.is(":checkbox") )
    error.appendTo ( element.next() );
  else
    error.appendTo( element.parent().next() );
}

Copy after login

程式碼的作用是:一般情況下把錯誤訊息顯示在 中,如果是radio 則顯示在 中,如果是checkbox 則顯示在內容的後面。
參數 類型 描述 預設值
errorClass String 指定錯誤提示的 css 類別名,可自訂錯誤提示的樣式。 "error"
errorElement String 用什麼標籤標記錯誤,預設是 label,可以改成 em。 "label"
errorContainer Selector 顯示或隱藏驗證訊息,可自動實作有錯誤訊息出現時把容器屬性變成顯示,無錯誤時隱藏,用處不大。
errorContainer: "#messageBox1, #messageBox2" 
errorLabelContainer Selector 把錯誤訊息統一放在一個容器裡面。 
wrapper String 用什麼標籤再包上邊的 errorELement。 
一般這三個屬性同時使用,實現在一個容器內顯示所有錯誤提示的功能,並且沒有資訊時自動隱藏。
errorContainer: "div.error",
errorLabelContainer: $("#signupForm div.error"),
wrapper: "li"
5、更改錯誤訊息顯示的樣式
設定錯誤提示的樣式,可以增加圖示顯示,在該系統中已經建立了一個 validation.css,專門用於維護校驗文件的樣式。

input.error { border: 1px solid red; }
label.error {
 background:url("./demo/images/unchecked.gif") no-repeat 0px 0px;

 padding-left: 16px;

 padding-bottom: 2px;

 font-weight: bold;

 color: #EA5200;
}
label.checked {
 background:url("./demo/images/checked.gif") no-repeat 0px 0px;
}

Copy after login

6、每個欄位驗證通過執行函數
success:String,Callback
要驗證的元素經過驗證後的動作,如果跟一個字串,會當作一個 css 類,也可跟一個函數。

success: function(label) {
  // set   as text for IE
  label.html(" ").addClass("checked");
  //label.addClass("valid").text("Ok!")
}
Copy after login

新增 "valid" 到驗證元素,在 CSS 中定義的樣式
success: "valid"
7、驗證的觸發方式修改
下面的雖然是 boolean 型的,但建議除非要改為 false,否則別亂加。
觸發方式 類型 描述 預設值
onsubmit Boolean 提交時驗證。設定為 false 就用其他方法去驗證。 true
onfocusout Boolean 失去焦點時驗證(不包括複選框/單選按鈕)。 true
onkeyup Boolean 在 keyup 時驗證。 true
onclick Boolean 在點選複選框和單選按鈕時驗證。 true
focusInvalid Boolean 提交表單後,未通過驗證的表單(第一個或提交先前獲得焦點的未通過驗證的表單)會獲得焦點。 true
focusCleanup Boolean 如果是 true 那麼當未通過驗證的元素獲得焦點時,移除錯誤提示。避免和 focusInvalid 一起用。 false

// 重置表单
$().ready(function() {
 var validator = $("#signupForm").validate({
    submitHandler:function(form){
      alert("submitted");  
      form.submit();
    }  
  });
  $("#reset").click(function() {
    validator.resetForm();
  });

});

Copy after login

8、非同步驗證
remote:URL
使用 ajax 方式進行驗證,預設會提交目前驗證的值到遠端位址,如果需要提交其他的值,可以使用 data 選項。

remote: "check-email.php"
remote: {
  url: "check-email.php",   //后台处理程序
  type: "post",        //数据发送方式
  dataType: "json",      //接受数据格式  
  data: {           //要传递的数据
    username: function() {
      return $("#username").val();
    }
  }
}
Copy after login

远程地址只能输出 "true" 或 "false",不能有其他输出。
9、添加自定义校验
addMethod:name, method, message
自定义验证方法

// 中文字两个字节
jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {
  var length = value.length;
  for(var i = 0; i < value.length; i++){
    if(value.charCodeAt(i) > 127){
      length++;
    }
  }
 return this.optional(element) || ( length >= param[0] && length <= param[1] );  
}, $.validator.format("请确保输入的值在{0}-{1}个字节之间(一个中文字算2个字节)"));

// 邮政编码验证  
jQuery.validator.addMethod("isZipCode", function(value, element) {  
  var tel = /^[0-9]{6}$/;
  return this.optional(element) || (tel.test(value));
}, "请正确填写您的邮政编码");

Copy after login

注意:要在 additional-methods.js 文件中添加或者在 jquery.validate.js 文件中添加。建议一般写在 additional-methods.js 文件中。
注意:在 messages_cn.js 文件中添加:isZipCode: "只能包括中文字、英文字母、数字和下划线"。调用前要添加对 additional-methods.js 文件的引用。
10、radio 和 checkbox、select 的验证
radio 的 required 表示必须选中一个。

<input type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />
<input type="radio" id="gender_female" value="f" name="gender"/>
checkbox 的 required 表示必须选中。
<input type="checkbox" class="checkbox" id="agree" name="agree" class="{required:true}" />
checkbox 的 minlength 表示必须选中的最小个数,maxlength 表示最大的选中个数,rangelength:[2,3] 表示选中个数区间。
<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, minlength:2}" />
<input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" />
<input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />
select 的 required 表示选中的 value 不能为空。
<select id="jungle" name="jungle" title="Please select something!" class="{required:true}">
  <option value=""></option>
  <option value="1">Buga</option>
  <option value="2">Baga</option>
  <option value="3">Oi</option>
</select>
select 的 minlength 表示选中的最小个数(可多选的 select),maxlength 表示最大的选中个数,rangelength:[2,3] 表示选中个数区间。
<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">
  <option value="b">Banana</option>
  <option value="a">Apple</option>
  <option value="p">Peach</option>
  <option value="t">Turtle</option>
</select>
Copy after login

附表:内置验证方式:

以上就是针对jQuery Validate表单验证的深入学习,希望对大家的学习有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!