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 if(value.charCodeAt(i) > 127){
length ;
}
}
return this.optional(element) | | ( length >= param[0] && length }, $.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

实现方法:1、用“$("img").delay(毫秒数).fadeOut()”语句,delay()设置延迟秒数;2、用“setTimeout(function(){ $("img").hide(); },毫秒值);”语句,通过定时器来延迟。

区别:1、axios是一个异步请求框架,用于封装底层的XMLHttpRequest,而jquery是一个JavaScript库,只是顺便封装了dom操作;2、axios是基于承诺对象的,可以用承诺对象中的方法,而jquery不基于承诺对象。

修改方法:1、用css()设置新样式,语法“$(元素).css("min-height","新值")”;2、用attr(),通过设置style属性来添加新样式,语法“$(元素).attr("style","min-height:新值")”。

增加元素的方法:1、用append(),语法“$("body").append(新元素)”,可向body内部的末尾处增加元素;2、用prepend(),语法“$("body").prepend(新元素)”,可向body内部的开始处增加元素。

在jquery中,apply()方法用于改变this指向,使用另一个对象替换当前对象,是应用某一对象的一个方法,语法为“apply(thisobj,[argarray])”;参数argarray表示的是以数组的形式进行传递。

删除方法:1、用empty(),语法“$("div").empty();”,可删除所有子节点和内容;2、用children()和remove(),语法“$("div").children().remove();”,只删除子元素,不删除内容。

on()方法有4个参数:1、第一个参数不可省略,规定要从被选元素添加的一个或多个事件或命名空间;2、第二个参数可省略,规定元素的事件处理程序;3、第三个参数可省略,规定传递到函数的额外数据;4、第四个参数可省略,规定当事件发生时运行的函数。

去掉方法:1、用“$(selector).removeAttr("readonly")”语句删除readonly属性;2、用“$(selector).attr("readonly",false)”将readonly属性的值设置为false。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

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