Instructions for using jquery.validate_jquery
1. Preparation
Requires JQuery version: 1.2.6, compatible with 1.3.2
Official website address: http://jqueryvalidation.org/
2. Default verification rules
(1)required:true required field
(2)remote:"check.php" Use the ajax method to call check.php to verify the input value
(3)email:true You must enter an email in the correct format
(4)url:true You must enter a URL in the correct format
(5)date:true You must enter a date in the correct format
( 6)dateISO:true You must enter the date (ISO) in the correct format, for example: 2009-06-23, 1998/01/22 Only verify the format, not the validity
(7)number:true You must enter a legal number (Negative number, decimal)
(8)digits:true must enter an integer
(9)creditcard: must enter a legal credit card number
(10)equalTo:"#field" The input value must be the same as #field
(11)accept: Enter a string with a legal suffix (the suffix of the uploaded file)
(12)maxlength:5 Enter a string with a maximum length of 5 (Chinese characters count as one character)
(13 )minlength:10 Enter a string with a minimum length of 10 (Chinese characters count as one character)
(14)rangelength:[5,10] Enter a string whose length must be between 5 and 10") (Chinese characters count as one characters)
(15)range:[5,10] The input value must be between 5 and 10
(16)max:5 The input value cannot be greater than 5
(17)min:10 Input value Cannot be less than 10
3. Default prompt
messages: {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url : "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date (ISO).",
dateDE: "Bitte geben Sie ein g eyebrow ltiges Datum ein.",
number: "Please enter a valid number.",
numberDE: "Bitte geben Sie eine Nummer ein.",
digits: "Please enter only digits",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
maxlength: $.validator.format("Please enter no more than {0} characters."),
minlength: $.validator.format("Please enter at least {0} characters."),
rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
range: $.validator.format("Please enter a value between {0} and {1 }."),
max: $.validator.format("Please enter a value less than or equal to {0}."),
min: $.validator.format("Please enter a value greater than or equal to {0}.")
},
If you need to modify it, you can add it to the js code:
jQuery.extend(jQuery.validator.messages, {
required: "Required field",
remote: "Please correct this field",
email: "Please enter a correct format of email",
url: "Please enter a legal URL",
date: "Please enter a legal date",
dateISO: "Please enter a legal date (ISO).",
number: "Please enter a legal number",
digits: "Only integers can be entered",
creditcard: "Please enter a legal date Credit card number",
equalTo: "Please enter the same value again",
accept: "Please enter a string with a legal suffix",
maxlength: jQuery.validator.format("Please enter a A string with a length of at least {0}"),
minlength: jQuery.validator.format("Please enter a string with a length of at least {0}"),
rangelength: jQuery.validator.format( "Please enter a string with a length between {0} and {1}"),
range: jQuery.validator.format("Please enter a value between {0} and {1} "),
max: jQuery.validator.format("Please enter a value with a maximum of {0}"),
min: jQuery.validator.format("Please enter a value with a minimum of {0} ")
});
Recommended practice is to put this file into messages_cn.js and introduce into the page
4. How to use
1. Write the verification rules into the control
使用class="{}"的方式,必须引入包:jquery.metadata.js 可以使用如下的方法,修改提示内容:
class="{required:true,minlength:5,messages: {required:'请输入内容'}}"在使用equalTo关键字时,后面的内容必须加上引号,如下代码:
class=" {required:true,minlength:5,equalTo:'#password'}"另外一个方式,使用关键字:meta(为了元数据使用其他插件你要包装 你的验证规则 在他们自己的项目中可以用这个特殊的选项)
Tell the validation plugin to look inside a validate-property in metadata for validation rules.
例如:
meta: "validate"
再有一种方式:
$.metadata.setType("attr", "validate");这样可以使用validate="{required:true}"的方式,或者class="required",但class="{required:true,minlength:5}"将不起作用 2.将校验规则写到代码中
$().ready(function() {
$("#signupForm").validate({
rules: {
firstname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
}
},
messages: {
firstname: "请输入姓名",
email: {
required: "请输入Email地址",
email: "请输入正确的email地址"
},
password: {
required: "请输入密码",
minlength: jQuery.format("密码不能小于{0}个字符")
},
confirm_password: {
required: "请输入确认密码",
minlength: "确认密码不能小于5个字符",
equalTo: "两次输入密码不一致不一致"
}
}
});
});//messages处,如果某个控件没有message,将调用默认的信息
required:true 必须有值
required:"#aa:checked" 表达式的值为真,则需要验证
required:function(){}返回为真,表时需要验证
后边两种常用于,表单中需要同时填或不填的元素
五、常用方法及注意问题
1.用其他方式替代默认的SUBMIT$().ready(function() {
$("#signupForm").validate({
submitHandler:function(form){
alert("submitted");
form.submit();
}
});
});
可以设置validate的默认值,写法如下:
$.validator.setDefaults({
submitHandler: function(form) { alert("submitted!");form.submit(); }
});
如果想提交表单, 需要使用form.submit()而不要使用$(form).submit()
2.debug,如果这个参数为true,那么表单不会提交,只进行检查,调试时十分方便
$().ready(function() {
$("#signupForm").validate({
debug:true
});
});
如果一个页面中有多个表单,用
$.validator.setDefaults({
debug: true
})
3.ignore:忽略某些元素不验证
ignore: ".ignore"
4.errorPlacement:Callback Default: 把错误信息放在验证的元素后面
指明错误放置的位置,默认情况是:error.appendTo(element.parent());即把错误信息放在验证的元素后面
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}//示例:
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: Under normal circumstances, the error message is displayed in , if it is radio, it is displayed in , if it is checkbox, it is displayed behind the content errorClass: String Default: "error"
Specify the css class name of the error prompt, and you can customize the style of the error prompt errorElement: String Default: "label"
What label should be used to mark errors? The default is label. You can change it to emerrorContainer: Selector
Showing or hiding verification information 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
Put error messages in a container. wrapper: String
What tag 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 errorContainer when there is no information: "div.error",
errorLabelContainer: $("#signupForm div.error"),
wrapper: "li" Set the style of the error prompt, you can add an icon to display 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;
}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, style defined in CSS
success: "valid" nsubmit: Boolean Default: true
Verify when submitting. If set to false, use other methods to verify
onfocusout: Boolean Default: true
Losing focus is validation (excluding checkboxes/radio buttons)
onkeyup: Boolean Default: true
Verify at keyup.
onclick: Boolean Default: true
Validate on checkboxes and radio clicks
focusInvalid: Boolean Default: true
After the form is submitted, the form that fails validation (the first or failed validation form that received focus before submission) will gain focus
focusCleanup: Boolean Default: false
If true then remove the error message when an element that fails validation gets focus. Avoid using it together with focusInvalid // Reset the form
$( ).ready(function() {
var validator = $("#signupForm").validate({
submitHandler:function(form){
alert("submitted");
form. submit();
}
});
$("#reset").click(function() {
validator.resetForm();
});});
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: {
url: "check-email.php", //Backend handler
type: "post", //Data sending method
dataType: "json", //Accept data format
data: { //Data to be transferred
username: function() {
return $( "#username").val();
}
}
}
The remote address can only output "true" or "false", and cannot have other output addMethod: name, method, message
Custom verification method
// Two bytes of Chinese characters
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("Please ensure that the entered value is within {0}-{1} bytes (One Chinese character counts as 2 bytes)"));
// Postal code verification
jQuery.validator.addMethod("isZipCode", function(value, element) {
var tel = / ^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, "Please fill in your zip code correctly");
The verification of radio and checkbox and select requires that one must be selected
The required in checkbox means that it must be selected
The minlength of checkbox indicates the minimum number of items that must be selected, and maxlength indicates the maximum number of items that must be selected. rangelength:[2,3] represents the selected number range
required in select means that the selected value cannot be empty
< ;select id="jungle" name="jungle" title="Please select something!" class="{required:true}">
Copy the code
required in select means that the selected value cannot be empty
>The minlength of select represents the minimum number of selected items (multi-selectable select), maxlength represents the maximum selected number, and rangelength:[2,3] represents the selected number range

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,

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: <

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: 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:

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

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
