Home Web Front-end JS Tutorial Introduction to the use of jQuery.Validate verification library_jquery

Introduction to the use of jQuery.Validate verification library_jquery

May 16, 2016 pm 05:35 PM

jQuery.Validate verification library
1. Download jquery.validate, here I provide jquery-validation-1.9.0, click to download

Default validation rules

Copy code The code is as follows:

(1)required:true           Required fields
(2)remote:"check.php"                                                                                                                                                                                                              but  🎜>(4)url:true You must enter the URL in the correct format
(5)date:true You must enter the 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 legal numbers (negative numbers, decimals)
(8)digits:true You must enter an integer
(9)creditcard: You 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 ( 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] Input a string whose length must be between 5 and 10") (Chinese characters count as one character)
(15)range:[5,10] Input value Must be between 5 and 10
(16)max:5 The input value cannot be greater than 5
(17)min:10 The input value cannot be less than 10


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 gumeltiges 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, save the following js code as: messages_cn.js and quote it on the page:
Copy the code The code is as follows:



Copy code The code is as follows:

jQuery.extend(jQuery.validator.messages, {
required : "Required field",
remote: "Please correct this field",
email: "Please enter a correct email format",
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 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 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 length between A value between {0} and {1}"),
max: jQuery.validator.format("Please enter a value up to {0}"),
min: jQuery.validator.format ("Please enter a minimum value of {0}")
});

Usage method
1. Write the verification rules into the control
Copy code The code is as follows:



< ;script language="JavaScript" type="text/JavaScript" src="jquery.validate.min.js">

<script><br>$().ready(function() {<br> $("#signupForm").validate();<br>});<br></script>


                                                                







< ;label for="password">Password







< input class="submit" type="submit" value="Submit"/>





Use class="{} " method, you must introduce the package: jquery.metadata.js


You can use the following method to modify the prompt content




The above code means: If the firstname field does not fill in any content, it will prompt: Please enter the content. So, if the length of the filled-in content is less than 5, how should the user be prompted to write? Please look at the code below:


Copy the code The code is as follows:



Note: When using the equalTo keyword, the following content must be enclosed in quotation marks, as shown in the following code:
Copy code The code is as follows:

class="{required:true,minlength:5,equalTo:'#password'}"

Another way, use the keyword: meta

For example, change the code in the above example to the keyword meta form, the code is as follows:

Copy the code The code is as follows:




<script><br>$().ready(function() {<br> $("#signupForm").validate({meta: "validate"});<br>});<br></script>


                                                                
















Note:


The rules section applies the full form as follows:

Correct writing:




Incorrect writing:




There is another way


$.metadata.setType("attr", "validate");


This way you can use validate="{required:true}", or class="required ", but class="{required:true,minlength:5}" will not work

For example, change the above example code to:


Copy the code The code is as follows:




<script><br>$().ready(function() {<br>  $.metadata.setType("attr", "validate");<br>  $("#signupForm").validate();<br>});<br></script>


   


       
   
 


 
 
 


 


 
 
 


 


 
 
 


   


       
   




注意:规则部分应用完整形式,即

正确写法:

复制代码 代码如下:



错误写法:
复制代码 代码如下:



2、将校验规则写到代码中
复制代码 代码如下:





<script><br>$().ready(function() {<br>  $("#signupForm").validate({<br>    rules:<br>    {<br>      firstname: "required",<br>      email:<br>      {<br>        required: true,<br>        email: true<br>      },<br>      password:<br>      {<br>        required: true,<br>        minlength: 5<br>      },<br>      confirm_password:<br>      {<br>        required: true,<br>        minlength: 5,<br>        equalTo: "#password"<br>      }<br>    },<br>    messages:<br>    {<br>      firstname: "请输入姓名",<br>      email:<br>      {<br>        required: "请输入Email地址",<br>        email: "请输入正确的email地址"<br>      },<br>      password:<br>      {<br>        required: "请输入密码",<br>        minlength: jQuery.format("密码不能小于{0}个字符")<br>      },<br>      confirm_password:<br>      {<br>        required: "请输入确认密码",<br>        minlength: "确认密码不能小于5个字符",<br>        equalTo: "两次输入密码不一致不一致"<br>      }<br>    }<br>  });<br>});<br>//messages处,如果某个控件没有message,将调用默认的信息<br></script>

   


       
       
   


 


 
 
 


 


 
 
 


 


 
 
 


   


       
   




required:true 必须有值

required:"#aa:checked"id名称为aa的dom被选中时,则需要验证

required:function(){} 返回为真,表示需要验证(仅针对required有效,其它无效。)

后边两种常用于,表单中需要同时填或不填的元素


下面针对上面三项内容,通过实例来说明一下,更易于理解。(第一个说明:required:true 必须有值 这项就不在举例了,通过上面的示例,已经非常清楚。)

required:"#aa:checked" 的示例如下:

复制代码 代码如下:





<script><br>$().ready(function() {<br>  $("#signupForm").validate({<br>    rules:<br>    {<br>      firstname: "required",<br>      email:<br>      {<br>        required: "#open:checked",<br>        email: true<br>      }<br>    },<br>    messages:<br>    {<br>      firstname: "请输入姓名",<br>      email:<br>      {<br>        required: "请输入Email地址",<br>        email: "请输入正确的email地址"<br>      }<br>    }<br>  });<br>});<br>//messages处,如果某个控件没有message,将调用默认的信息<br></script>

   


        开关:
       
       
       
       
   


   


     
     
   


   


       
   




当选中“打开”时,则对email进行验证。

required:function(){}的示例如下:

复制代码 代码如下:





<script><br>$().ready(function() {<br>  $("#signupForm").validate({<br>    rules:<br>    {<br>      firstname: "required",<br>      email:<br>      {<br>        required: function()<br>        {<br>          return true;<br>        },<br>        email: function()<br>        {<br>          return false;<br>        }<br>      }<br>    },<br>    messages:<br>    {<br>      firstname: "请输入姓名",<br>      email:<br>      {<br>        required: "请输入Email地址",<br>        email: "请输入正确的email地址"<br>      }<br>    }<br>  });<br>});<br>//messages处,如果某个控件没有message,将调用默认的信息<br></script>

   


        开关:
       
       
       
       
   


   


     
     
   


   


       
   




经过测试得知,即使email:function(){return false}); 是返回false,但是required:function(){return true;},是返回true,那么,除了验证是否为空外,还验证email格式。也就是说email:function(){reuturn false;}设置无效。进一步测试,去掉required:function(){return true;},只保留:email:function(){reuturn false;},仍然验证email格式。代码如下:
复制代码 代码如下:

  $("#signupForm").validate({
    rules:
    {
      firstname: "required",
      email:
      {
        email: function()
        {
          return false;
        }
      }
    },
    messages:
    ......

注意:将校验规则单独写在文件中,如上面例子中的rules规则中的firstname,email等,问题是,在input中有id,又有name属性,那JQuery Validation获取哪个呢?通过测试,是获取name属性的。所以,rules中的key,是input的name属性值,而不是id属性值。

定义样式代码

复制代码 代码如下:

/* jQuery.Validate css */
input.error{border: 1px dotted red;}
label.error{
  background-image:url('del.gif');
  background-repeat:no-repeat;
  padding-left:18px;
  color: red;
}

input.error defines the style of the input control

label.error defines the style of the error message

As shown below:

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles