The previous article introduced the basic knowledge of jQuery Validate form validation. For details, please refer to "JQuery Validate Form Validation Getting Started Learning" , Today’s This article provides an in-depth study of jQuery Validate form validation. The following is the entire content of the article:
1. Use other methods to replace the default SUBMIT
$().ready(function() { $("#signupForm").validate({ submitHandler:function(form){ alert("submitted"); form.submit(); } }); });
Use ajax method
$(".selector").validate({ submitHandler: function(form) { $(form).ajaxSubmit(); } })
You can set the default value of validate, which is written as follows:
$.validator.setDefaults({ submitHandler: function(form) { alert("submitted!");form.submit(); } });
If you want to submit a form, you need to use form.submit() instead of $(form).submit().
2. Debug, only verify but not submit the form
If this parameter is true, the form will not be submitted and will only be checked, which is very convenient for debugging.
$().ready(function() { $("#signupForm").validate({ debug:true }); });
If there are multiple forms on a page and you want to set them to debug, use:
$.validator.setDefaults({ debug: true })
3. ignore: ignore certain elements and do not verify
ignore: ".ignore"
4. Change the position where the error message is displayed
errorPlacement: Callback
Indicates the location where the error is placed. The default is: error.appendTo(element.parent()); that is, the error message is placed after the verified element.
errorPlacement: function(error, element) { error.appendTo(element.parent()); }
Example
<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() ); }
The function of the code is: generally, the error message is displayed inf66f4b1ecdd4fba772d761f0fc7b8c71b90dd5946f0946207856a8a37f441edf, if it is radio, it is displayed In b6c5a531a458a2e790c1fd6421739d1cb90dd5946f0946207856a8a37f441edf, if it is a checkbox, it is displayed behind the content.
Parameter Type Description Default Value
errorClass String specifies the css class name of the error prompt, and you can customize the style of the error prompt. "error"
errorElement String What label is used to mark errors? The default is label, which can be changed to em. "label"
errorContainer Selector displays or hides verification information. It can automatically change the container properties to display when an error message appears, and hide it when there is no error. It is of little use.
errorContainer: "#messageBox1, #messageBox2"
errorLabelContainer Selector puts error information in a container.
wrapper String What label should be used to wrap the errorELement above.
Generally, these three attributes are used at the same time to realize the function of displaying all error prompts in a container and automatically hiding it when there is no information.
errorContainer: "div.error",
errorLabelContainer: $("#signupForm div.error"),
wrapper: "li"
5. Change the style of error message display
Set the style of error prompts and add icon display. A validation.css has been created in this system, which is specifically used to maintain the style of the verification file.
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. Each field is verified through the execution function
success:String,Callback
The action after the element to be verified passes verification. If it is followed by a string, it will be treated as a css class, or it can be followed by a function.
success: function(label) { // set as text for IE label.html(" ").addClass("checked"); //label.addClass("valid").text("Ok!") }
Add "valid" to the validation element with the style defined in CSS c9ccee2e6ea535a969eb3f532ad9fe89label.valid {}531ac245ce3e4fe3d50054a55f265927.
success: "valid"
7. Modification of verification triggering method
Although the following is of boolean type, it is recommended not to add it randomly unless you want to change it to false.
Trigger method type description default value
onsubmit Boolean Validated on submission. Set to false to use other methods to verify. true
onfocusout Boolean Validates when focus is lost (excluding checkboxes/radio buttons). true
onkeyup Boolean Validated during keyup. true
onclick Boolean Validates when checkboxes and radio buttons are clicked. true
focusInvalid Boolean After the form is submitted, the form that fails validation (the first or failed validation form that received focus before submission) will gain focus. true
focusCleanup Boolean If true then removes the error message when an element that fails validation gains focus. Avoid using it with focusInvalid. false
// 重置表单 $().ready(function() { var validator = $("#signupForm").validate({ submitHandler:function(form){ alert("submitted"); form.submit(); } }); $("#reset").click(function() { validator.resetForm(); }); });
8. Asynchronous verification
remote: URL
Use ajax for verification. By default, the currently verified value will be submitted to the remote address. If you need to submit other values, you can use the data option.
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表单验证的深入学习,希望对大家的学习有所帮助。