Home > Web Front-end > JS Tutorial > Detailed explanation of jQuery validation plug-in Validate_jquery

Detailed explanation of jQuery validation plug-in Validate_jquery

PHP中文网
Release: 2016-05-16 16:31:03
Original
1237 people have browsed it

validate is a good jq plug-in that provides powerful validation functions, making client form validation easier. It also provides a large number of customization options to meet various application needs. The plugin bundles a set of useful validation methods, including URL and email validation, and provides an API for writing user-defined methods.

The most common occasion for using JavaScript is form validation, and jQuery, as an excellent JavaScript library, also provides an excellent form validation plug-in----Validation. Validation is one of the oldest jQuery plug-ins, has been verified by different projects around the world, and has been praised by many web developers. As a standard verification method library, Validation has the following characteristics:

1. Built-in validation rules: It has 19 types of built-in validation rules such as required, numbers, emails, URLs and credit card numbers
2. Customization Verification rules: Verification rules can be easily customized
3. Simple and powerful verification information prompts: Verification information prompts are provided by default, and the function of customizing the default prompt information is provided
4. Real-time verification: Possible to pass The keyup or blur event triggers validation, not just when the form is submitted

validate.js download address: http://plugins.jquery.com/project/validate
metadata.js download address: http://plugins.jquery.com/project/metadata Usage:


1. Introduce the jQuery library and Validation plug-in

The code is as follows :

<script src="scripts/jquery-1.6.4.js" type="text/javascript"></script>  
<script src="scripts/jquery.validate.js" type="text/javascript"></script>
Copy after login

2. Determine which form needs to be verified

The code is as follows:

<script type="text/javascript">  
////<![CDATA[  
$(document).ready(function(){  
    $("#commentForm").validate();  
});  
//]]>  
</script>
Copy after login

3. Code verification rules for different fields and set the corresponding attributes of the fields

The code is as follows:

class="required"   必须填写  
class="required email"        必须填写且内容符合Email格式验证  
class="url"             符合URL格式验证  
minlength="2"      最小长度为2  
可验证的规则有19种:
[javascript] view plaincopyprint?
required:      必选字段  
remote:        "请修正该字段",  
email:         电子邮件验证  
url:           网址验证  
date:          日期验证  
dateISO:       日期 (ISO)验证  
dateDE:  
number:        数字验证  
numberDE:  
digits:        只能输入整数  
creditcard:    信用卡号验证  
equalTo:       ”请再次输入相同的值“验证  
accept:        拥有合法后缀名的字符串验证  
maxlength/minlength:    最大/最小长度验证  
rangelength:     字符串长度范围验证  
range:           数字范围验证  
max/min:         最大值/最小值验证
Copy after login

needs to be introduced The js

code is as follows:

<script type="text/javascript" src="../../scripts/jquery-1.3.1.js"></script>
<script type="text/javascript" src="lib/jquery.validate.js"></script>
Copy after login

The initialized HTML

code is as follows:

<script type="text/javascript">
$(function(){
 $("#commentForm").validate() 
})
</script>
<form class="cmxform" id="commentForm" method="get" action="">
 <fieldset>
   <legend>一个简单的validate验证带验证提示的评论例子</legend>
   <p>
     <label for="cusername">姓名</label>
     <em>*</em><input id="cusername" name="username" size="25" class="required" minlength="2" />
   </p>
   <p>
     <label for="cemail">电子邮件</label>
     <em>*</em><input id="cemail" name="email" size="25" class="required email"  />
   </p>
   <p>
     <label for="curl">网址</label>
     <em>  </em><input id="curl" name="url" size="25" class="url" />
   </p>
   <p>
     <label for="ccomment">你的评论</label>
     <em>*</em><textarea id="ccomment" name="comment" cols="22" class="required" ></textarea>
   </p>
 <p>
     <input class="submit" type="submit" value="提交"/>
   </p>
Copy after login

First look at the specifications of the default settings

Serial number
序号规则描述
1required:true必须输入的字段。
2remote:"check.php"使用 ajax 方法调用 check.php 验证输入值。
3email:true必须输入正确格式的电子邮件。
4url:true必须输入正确格式的网址。
5date:true必须输入正确格式的日期。日期校验 ie6 出错,慎用。
6dateISO:true必须输入正确格式的日期(ISO),例如:2009-06-23,1998/01/22。只验证格式,不验证有效性。
7number:true必须输入合法的数字(负数,小数)。
8digits:true必须输入整数。
9creditcard:必须输入合法的信用卡号。
10equalTo:"#field"输入值必须和 #field 相同。
11accept:输入拥有合法后缀名的字符串(上传文件的后缀)。
12maxlength:5输入长度最多是 5 的字符串(汉字算一个字符)。
13minlength:10输入长度最小是 10 的字符串(汉字算一个字符)。
14rangelength:[5,10]输入长度必须介于 5 和 10 之间的字符串(汉字算一个字符)。
15range:[5,10]输入值必须介于 5 和 10 之间。
16max:5输入值不能大于 5。
17min:10输入值不能小于 10。
Rule<🎜>Description<🎜>
1required:trueA field that must be entered.
2remote:"check.php"Use the ajax method to call check.php to verify the input value.
3email:trueYou must enter a correctly formatted email.
4url:trueYou must enter the URL in the correct format.
5date:trueA date in the correct format must be entered. Date verification ie6 error, use with caution.
6dateISO:trueYou 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.
7number:trueLegal numbers (negative numbers, decimals) must be entered.
8digits:trueAn integer must be entered.
9creditcard:A valid credit card number must be entered.
10equalTo:"#field"The input value must be the same as #field.
11accept:Enter a string with a legal suffix (the suffix of the uploaded file).
12maxlength:5Enter a string with a maximum length of 5 (Chinese characters count as one character).
13minlength:10Enter a string with a minimum length of 10 (Chinese characters count as one character).
14rangelength:[5,10]The input length must be between 5 and 10 ( Chinese characters count as one character).
15range:[5,10]The input value must be between 5 and 10.
16max:5The input value cannot be greater than 5.
17min:10The input value cannot be less than 10.

required表示必须填写的

email表示必须正确的邮箱

把验证的规格写在HTML内的class内,方法欠妥,后期的维护增加成本,没有实现行为与结构的分离

所以,可以想把HTML内的class都清空,如下:

代码如下:

<form class="cmxform" id="commentForm" method="get" action="">
 <fieldset>
   <legend>一个简单的validate验证带验证提示的评论例子</legend>
   <p>
     <label for="cusername">姓名</label>
     <em>*</em><input id="cusername" name="username" size="25" />
   </p>
   <p>
     <label for="cemail">电子邮件</label>
     <em>*</em><input id="cemail" name="email" size="25"  />
   </p>
   <p>
     <label for="curl">网址</label>
     <em>  </em><input id="curl" name="url" size="25" />
   </p>
   <p>
     <label for="ccomment">你的评论</label>
     <em>*</em><textarea id="ccomment" name="comment" cols="22" ></textarea>
   </p>
 <p>
     <input class="submit" type="submit" value="提交"/>
   </p>
Copy after login

js

代码如下:

 $(document).ready(function(){
    $("#commentForm").validate({
      rules:{
        username:{
          required:true,
          minlength:2
        },
        email:{
          required:true,
          email:true
        },
        url:"url",
        comment:"required",
        valcode: {
          formula: "7+9"  
        }
      }
    });
  });
  </script>
Copy after login

因为默认的提示是英文的,可以改写成

代码如下:

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

建议新建一个js,放到validate.js 下面.

关于提示的美化

代码如下:

errorElement:"em"
Copy after login

  创建一个标签,可以自定义

代码如下:

success:function(label){
        label.text(" ").addClass(&#39;success&#39;)
      }
Copy after login

这里的参数label是指向创建的标签,这里也就是”em“ 然后情况自己的内容,在加上自己的class就可以了

完整的js

代码如下:

  $("#commentForm").validate({
      rules:{
        username:{
          required:true,
          minlength:2
        },
        email:{
          required:true,
          email:true
        },
        url:"url",
        comment:"required",
      },
      errorElement:"em",
      success:function(label){
        label.text(" ").addClass(&#39;success&#39;)
      }
    });
Copy after login

相对应的css

代码如下:

em.error {
  background:url("images/unchecked.gif") no-repeat 0px 0px;
  padding-left: 16px;
}
em.success {
  background:url("images/checked.gif") no-repeat 0px 0px;
  padding-left: 16px;
}
Copy after login

.success放到.error下面。。。唔唔。。具体的情况。。只可体会不可言会。。唔。。

在做项目的过程中千变万化,有时候要满足不同的需求,validate也可以单独的修改验证的信息。。

例如:

代码如下:

  messages:{
        username:{
          required:"主人,我要填的满满的",
          minlength:"哎唷,长度不够耶"
        }
   }
Copy after login

完整的js

代码如下:

 $("#commentForm").validate({
      rules:{
        username:{
          required:true,
          minlength:2
        },
        email:{
          required:true,
          email:true
        },
        url:"url",
        comment:"required",
        valcode: {
          formula: "7+9"  
        }
      },
      messages:{
        username:{
          required:"主人,我要填的满满的",
          minlength:"哎唷,长度不够耶"
        }
      },
      errorElement:"em",
      success:function(label){
        label.text(" ").addClass(&#39;success&#39;)
      }
    });
Copy after login

这里就可以啦。

关于自定义验证规则

增加一段HTML代码

代码如下:

 <p>
     <label for="cvalcode">验证码</label>
     <input id="valcode" name="valcode"  />=7+9
   </p>
Copy after login

自定一个规则

代码如下:

$.validator.addMethod("formula",function(value,element,param){
      return value==eval(param)
    },"请正确输入验证信息");
Copy after login

formula是需要验证方法的名字 好比如required 必须的。
value返回的当前input的value值
param返回的是当前自定义的验证格式 好比如:7+9
在试用了eval方法 让字符串相加

完整的js

代码如下:

$.validator.addMethod("formula",function(value,element,param){
      return value==eval(param)
    },"请正确输入验证信息");
    $("#commentForm").validate({
      rules:{
        username:{
          required:true,
          minlength:2
        },
        email:{
          required:true,
          email:true
        },
        url:"url",
        comment:"required",
        valcode: {
          formula: "7+9"  
        }
      },
      messages:{
        username:{
          required:"主人,我要填的满满的",
          minlength:"哎唷,长度不够耶"
        }
      },
      errorElement:"em",
      success:function(label){
        label.text(" ").addClass(&#39;success&#39;)
      }
    });
Copy after login

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template