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)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
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.

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.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

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: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

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.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

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.

How do I install JavaScript? How do I install JavaScript? Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles