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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months 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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.