之前一篇文章介紹了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表单验证的深入学习,希望对大家的学习有所帮助。

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor