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: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools