search
HomeWeb Front-endJS TutorialjQuery validate验证插件使用详解_jquery

Validate验证插件,内置丰富的验证规则,还有灵活的自定义规则接口,HTML、CSS与JS之间的低耦合能让您自由布局和丰富样式,支持input,select,textarea的验证。

Description

浏览器支持:IE7+ 、Chrome、Firefox、Safari、Mobile Browser

jQuery版本:1.7.0+

Usage
载入jQuery、validate



DOM标签验证规则填写

<div class="form_control">
 <input class="required" value="315359131@qq.com" type="text" name="email" data-tip="请输入您的邮箱" data-valid="isNonEmpty||isEmail" data-error="email不能为空||邮箱格式不正确">
</div>
<div class="form_control">
 <select class="required" data-valid="isNonEmpty" data-error="省份必填">
  <option value="">请选择省份</option>
  <option value="001">001</option>
  <option value="002">002</option>
 </select>
</div>

给需要验证的表单元素的class填入required(不建议在这个class上做其他样式)。
建议input用独立div包裹,因为验证的message是从当前input的父元素上append生成。
data-tip:在尚未验证而获取焦点时出现的提示。
data-valid:验证规则,若有组合验证,以||符号分割。
data-error:验证错误提示,对应data-valid,以||符号分割。
单选/复选比较特殊,需要添加元素包裹单选/复选集合,并在包裹元素上加验证规则。

<div class="form_control">
 <span class="required" data-valid="isChecked" data-error="性别必选" data-type="radio">
   <label><input type="radio" name="sex">男</label>
   <label><input type="radio" name="sex">女</label>
   <label><input type="radio" name="sex">未知</label>
 </span>
</div>
<div class="form_control">
 <span class="required" data-valid="isChecked" data-error="标签至少选择一项" data-type="checkbox">
   <label><input type="checkbox" name="label">红</label>
   <label><input type="checkbox" name="label">绿</label>
   <label><input type="checkbox" name="label">蓝</label>
 </span>
</div>

JS调用

//**注意:必须以表单元素调用validate**
 $('form').validate({
  type:{
   isChecked: function(value, errorMsg, el) {
    var i = 0;
    var $collection = $(el).find('input:checked');
    if (!$collection.length) {
     return errorMsg;
    }
   }
  },
  onFocus: function() {
   this.parent().addClass('active');
   return false;
  },
  onBlur: function() {
   var $parent = this.parent();
   var _status = parseInt(this.attr('data-status'));
   $parent.removeClass('active');
   if (!_status) {
    $parent.addClass('error');
   }
   return false;
  }
 });

表单提交前的验证

 $('form').on('submit', function(event) {
  event.preventDefault();
  $(this).validate('submitValidate'); //return true or false;
 });

validate内置验证规则

required:true 必输字段
remote:"check.php" 使用ajax方法调用check.php验证输入值
email:true 必须输入正确格式的电子邮件
url:true 必须输入正确格式的网址
date:true 必须输入正确格式的日期
dateISO:true 必须输入正确格式的日期(ISO),例如:2009-06-23,1998/01/22 只验证格式,不验证有效性
number:true 必须输入合法的数字(负数,小数)
digits:true 必须输入整数
creditcard: 必须输入合法的信用卡号
equalTo:"#field" 输入值必须和#field相同
accept: 输入拥有合法后缀名的字符串(上传文件的后缀)
maxlength:5 输入长度最多是5的字符串(汉字算一个字符)
minlength:10 输入长度最小是10的字符串(汉字算一个字符)
rangelength:[5,10] 输入长度必须介于 5 和 10 之间的字符串")(汉字算一个字符)
range:[5,10] 输入值必须介于 5 和 10 之间
max:5 输入值不能大于5
min:10 输入值不能小于10

例子:
验证用户名,密码,确认密码,主页,生日,邮箱
首先引入Jquery、引入jquery.validate.js、引入messages_cn.js并且为表单定义一个id,为需要验证的控件定义name属性,并赋值,此插件使用的是控件的name属性,而非id。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="jquery邮箱验证.aspx.cs" Inherits="练习.jquery邮箱验证" %>
<!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 runat="server">
  <title></title>
  <style type="text/css">
  #aa{ color:Red;}
  </style>
   <script src="Jquery1.7.js" type="text/javascript"></script>
  <script src="jquery.validate.js" type="text/javascript"></script>
  <script src="messages_cn.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {


    $('#form1').validate({
      rules: {
        username: { required: true, minlength: 6, maxlength: 12 },
        password: { required: true, minlength: 6 },
        passwordok:{required: true, equalTo: "#password"},
        index: { required: true, url: true },
        birthday: { required: true, dateISO: true },
        bloodpress:{required: true,digits:true},
        email: { required: true, email: true }
    },
    errorshow: function (error, element) {
      error.appendTo(element.siblings('span'));
    }

 })
    })
  
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
  <table>
  <tr><td>用户名:</td><td>
  <input name="username" type="text" /><span id="aa">*</span></td></tr>
  <tr><td>密码:</td><td>
  <input id="password" name="password" type="text" /><span id="aa">*</span></td></tr>
  <tr><td>确认密码:</td><td>
  <input id="repassword" name="passwordok" type="text" /><span id="aa">*</span></td></tr>
   <tr><td>主页:</td><td>
  <input name="index" type="text" /><span id="aa">*</span></td></tr>
  <tr><td>生日:</td><td>
  <input name="birthday" type="text" /><span id="aa">*</span></td></tr>
  <tr><td>血压:</td><td>
  <input name="bloodpress" type="text" /><span id="aa">*</span></td></tr>
 <tr><td>邮箱:</td><td><input name="email" type="text" /><span id="aa">*</span></td></tr>
 <tr><td></td><td>
  <input id="Button1" type="button" value="button" /></td></tr>
</table>
  </div>
  </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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

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.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development 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.