search
HomeWeb Front-endJS TutorialDetailed explanation of how to use jQuery Validation PlugIn_jquery

1. Necessary before use
Official website: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
API: http://jquery.bassistance.de/api-browser/plugins.html
Current version: 1.5.5
Requires JQuery version: 1.2.6+, compatible with 1.3.2


2. Default verification rules

  • (1)required:true Required fields
  • (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 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 the format is verified, not the validity
  • (7)number:true You must enter a legal number (negative number, decimal)
  • (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 (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] The input length must be a string between 5 and 10") (Chinese characters count as one character)
  • (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 The input value cannot be less than 10

3. Default prompts

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眉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: "必选字段", 
remote: "请修正该字段", 
email: "请输入正确格式的电子邮件", 
url: "请输入合法的网址", 
date: "请输入合法的日期", 
dateISO: "请输入合法的日期 (ISO).", 
number: "请输入合法的数字", 
digits: "只能输入整数", 
creditcard: "请输入合法的信用卡号", 
equalTo: "请再次输入相同的值", 
accept: "请输入拥有合法后缀名的字符串", 
maxlength: jQuery.validator.format("请输入一个长度最多是 {0} 的字符串"), 
minlength: jQuery.validator.format("请输入一个长度最少是 {0} 的字符串"), 
rangelength: jQuery.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"), 
range: jQuery.validator.format("请输入一个介于 {0} 和 {1} 之间的值"), 
max: jQuery.validator.format("请输入一个最大为 {0} 的值"), 
min: jQuery.validator.format("请输入一个最小为 {0} 的值") 
}); 

Recommended practice, Put this file into messages_cn.js and introduce it into the page
[codept src="../js/messages_cn.js" type="text/javascript"> [/code
4. How to use
1. Write the verification rules into the control

<script src="../js/jquery.js" type="text/javascript"></script> 
<script src="../js/jquery.validate.js" type="text/javascript"></script> 
<script src="./js/jquery.metadata.js" type="text/javascript"></script> 
$().ready(function() { 
$("#signupForm").validate(); 
}); 
 
<form id="signupForm" method="get" action=""> 
 <p> 
  <label for="firstname">Firstname</label> 
  <input id="firstname" name="firstname" class="required" /> 
 </p> 
<p> 
<label for="email">E-Mail</label> 
<input id="email" name="email" class="required email" /> 
</p> 
<p> 
<label for="password">Password</label> 
<input id="password" name="password" type="password" class="{required:true,minlength:5}" /> 
</p> 
<p> 
<label for="confirm_password">确认密码</label> 
<input id="confirm_password" name="confirm_password" type="password" class="{required:true,minlength:5,equalTo:'#password'}" /> 
</p> 
 <p> 
  <input class="submit" type="submit" value="Submit"/> 
 </p> 
</form> 

To use class="{}", the package must be imported: jquery.metadata.js
You can use the following method to modify the prompt content:

Copy code The code is as follows:
class="{required:true,minlength:5,messages:{required:' Please enter the content'}}"
 
在使用equalTo关键字时,后面的内容必须加上引号,如下代码: 
复制代码 代码如下:
class="{required:true,minlength:5,equalTo:'#password'}"
 
另外一个方式,使用关键字:meta(为了元数据使用其他插件你要包装 你的验证规则 在他们自己的项目中可以用这个特殊的选项) 
再有一种方式: 
$.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,将调用默认的信息 
 
<form id="signupForm" method="get" action=""> 
 <p> 
  <label for="firstname">Firstname</label> 
  <input id="firstname" name="firstname" /> 
 </p> 
<p> 
<label for="email">E-Mail</label> 
<input id="email" name="email" /> 
</p> 
<p> 
<label for="password">Password</label> 
<input id="password" name="password" type="password" /> 
</p> 
<p> 
<label for="confirm_password">确认密码</label> 
<input id="confirm_password" name="confirm_password" type="password" /> 
</p> 
 <p> 
  <input class="submit" type="submit" value="Submit"/> 
 </p> 
</form> 

required:true 必须有值 
required:"#aa:checked"表达式的值为真,则需要验证 
required:function(){}返回为真,表时需要验证 
后边两种常用于,表单中需要同时填或不填的元素  

五、实例讲解

实例一:精简验证,通过表单对象调用validate()方法进行验证,验证规则通过html标签属性定义:以下为常用属性定义距离

class='required'  //必须字段
class='mail'  //邮箱验证
class='url'  //URL网址验证
class='date'  //正确的日期 格式满足 2012,0204,2012-02-04
class='number'  //输入合法的数字
class='digits'  //输入整数
minlength=''  //最小输入长度
maxlength=''  //最长输入长度(该值不会提示,当值达到一定字符数不可再增长)
max=''  //输入的数值小于指定值
min=''  //输入的数值大于指定值

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>jQuery PlugIn - 表单验证插件实例 Validate </title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript" src="jquery.validate.min.js"></script>
 <script type="text/javascript" src="messages_cn.js"></script>
 <style type="text/css">
 * { font-family: Verdana; font-size:13px; }
 input[type='text']{width:200px;}
 textarea{width:155px;}
 label { width: 10em; float: left; }
 label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
 </style>
 <script>
 $(document).ready(function(){
  $("#commentForm").validate();
 });
 </script>
</head>
<body>
 <form id="commentForm" method="get" action="" >
 <fieldset>
 <legend>表单验证</legend>
 <p><label>Name</label><input name="name" class="required" maxlength="4" minlength="2" /></p>
 <p><label >E-Mail</label><input name="email" class="required email" /></p>
 <p><label >URL</label><input name="url" class="url"/></p>
 <p><label>text</label><textarea name="text" cols="22" class="required"></textarea></p>
 <p><input class="submit" type="submit" value="提交"/></p>
 </fieldset>
 </form>
</body>
</html>

实例二:方法验证,通过自定义表单规则来验证表单

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>jQuery PlugIn - 表单验证插件实例 Validate </title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript" src="jquery.validate.min.js"></script>
 <script type="text/javascript" src="messages_cn.js"></script>
 <style type="text/css">
 * { font-family: Verdana; font-size:13px; }
 input[type='text']{width:200px;}
 textarea{width:155px;}
 .title{float:left;width:10em}
 em.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
 .field_notice{display:none;}
 .checking{display:none;}
 </style>
 <script>
 $(document).ready(function(){
  $("#commentForm").validate({
   errorPlacement: function(error, element){
    var error_td = element.next('em');
    error_td.find('.field_notice').hide();
    error_td.append(error);
   },
   success: function(label){
    label.addClass('validate_right').text('OK!');
   },
   onkeyup: false,
   rules: {
    name: {
     required:true,
     minlength:3,
     maxlength:40,
     remote:{
      url :'index.php&#63;ajax=1',
      type:'get',
      data:{
       name : function(){
        return $('#name').val();
       }
      },
      beforeSend:function(){
       var _checking = $('#checking');
       _checking.prev('.field_notice').hide();
       _checking.next('label').hide();
       $(_checking).show();
      },
      complete :function(){
       $('#checking').hide();
      }
     }
    },
    email: {required: true, email: true },
    url:{required:true,url:true},
    text:"required"
   },
   messages: {
    name: {required:"需要输入名称", minlength:"名称长度在3-40个字符之间", maxlength:"名称长度在3-40个字符之间",remote:"用户名已存在"},
    email: {required:"需要输入电子邮箱", email:"电子邮箱格式不正确"},
    url: {required:"需要输入URL地址", url:"URL地址格式不正确"},
    text:"需要输入文本内容"
   },
  });
 });
 </script>
</head>
<body>
 <form id="commentForm" method="get" action="" >
 <fieldset>
 <legend>表单验证</legend>
 <p><label class="title" >Name</label><input id="name" name="name"/>
  <em><label class="field_notice"></label><label id="checking" class="checking">检查中...</label></em>
 </p>
 <p><label class="title" >E-Mail</label><input name="email"/>
  <em><label class="field_notice"></label></em>
 </p>
 <p><label class="title" >URL</label><input name="url"/>
  <em><label class="field_notice"></label></em>
 </p>
 <p><label class="title" >text</label><textarea name="text" cols="22"></textarea>
  <em><label class="field_notice"></label></em>
 </p>
 <p><input class="submit" type="submit" value="提交"/></p>
 </fieldset>
 </form>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助。

Statement
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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 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.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

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

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 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.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor