In-depth study of jQuery Validate form validation_jquery
之前一篇文章介紹了jQuery Validate表單驗證入門的基礎知識,詳細內容請參閱《jQuery Validate表單驗證入門學習》,今天這篇文章深入學習jQuery Validate表單驗證,以下是文章的全部內容:
1、用其他方式取代預設的 SUBMIT
$().ready(function() { $("#signupForm").validate({ submitHandler:function(form){ alert("submitted"); form.submit(); } }); });
使用 ajax 方式
$(".selector").validate({ submitHandler: function(form) { $(form).ajaxSubmit(); } })
可以設定 validate 的預設值,寫法如下:
$.validator.setDefaults({ submitHandler: function(form) { alert("submitted!");form.submit(); } });
如果想提交表單, 需要使用 form.submit(),而不要使用 $(form).submit()。
2、debug,只驗證不提交表單
如果這個參數是true,那麼表單就不會提交,只進行檢查,調試時十分方便。
$().ready(function() { $("#signupForm").validate({ debug:true }); });
如果一個頁面中有多個表單都想設定成為 debug,則使用:
$.validator.setDefaults({ debug: true })
3、ignore:忽略某些元素不驗證
ignore: ".ignore"
4、更改錯誤訊息顯示的位置
errorPlacement:Callback
指明錯誤放置的位置,預設情況是:error.appendTo(element.parent());即把錯誤訊息放在驗證的元素後面。
errorPlacement: function(error, element) { error.appendTo(element.parent()); }
實例
<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() ); }
程式碼的作用是:一般情況下把錯誤訊息顯示在
參數 類型 描述 預設值
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; }
6、每個欄位驗證通過執行函數
success:String,Callback
要驗證的元素經過驗證後的動作,如果跟一個字串,會當作一個 css 類,也可跟一個函數。
success: function(label) { // set as text for IE label.html(" ").addClass("checked"); //label.addClass("valid").text("Ok!") }
新增 "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(); }); });
8、非同步驗證
remote:URL
使用 ajax 方式進行驗證,預設會提交目前驗證的值到遠端位址,如果需要提交其他的值,可以使用 data 選項。
remote: "check-email.php" remote: { url: "check-email.php", //后台处理程序 type: "post", //数据发送方式 dataType: "json", //接受数据格式 data: { //要传递的数据 username: function() { return $("#username").val(); } } }
远程地址只能输出 "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)); }, "请正确填写您的邮政编码");
注意:要在 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>
附表:内置验证方式:
以上就是针对jQuery Validate表单验证的深入学习,希望对大家的学习有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s
