search
HomeWeb Front-endJS Tutorialjquery.validate form validation plug-in usage analysis

为什么要用jquery validate这个表单验证插件:自己写一个通用且功能全面强大的jquery表单验证插件并不容易。jquery validate这个jquery插件几乎可以轻松应对95%以上的表单验证,具体内容如下

使用方式

1、在控件中使用默认验证规则,例子:
电子邮件(必填) 

2、可以在控件中自定义验证规则,例子:
自定义(必填,[3,5])

<input id="complex" value="hi" class="{required:true,minlength:3, maxlength:5,
messages:{required:&#39;为什么不输入一点文字呢&#39;,minlength:&#39;输入的太少了&#39;,maxlength:&#39;输入那么多干嘛&#39;}}" />

   

3、通过javascript自定义验证规则,下面的JS自定义了两个规则,password和confirm_password

$().ready(function() {
 $("#form2").validate({
 rules: {
  password: {
  required: true,
  minlength: 5
  },
  confirm_password: {
  required: true,
  minlength: 5,
  equalTo: "#password"
  }
 },
 messages: {
  password: {
  required: "没有填写密码",
  minlength: jQuery.format("密码不能小于{0}个字符")
  },
  confirm_password: {
  required: "没有确认密码",
  minlength: "确认密码不能小于{0}个字符",
  equalTo: "两次输入密码不一致嘛"
  }
 }
 });
});

   

required除了设置为true/false之外,还可以使用表达式或者函数,比如

$("#form2").validate({
 rules: {
 funcvalidate: {
 required: function() {return $("#password").val()!=""; }
 }
 },
 messages: {
 funcvalidate: {
 required: "有密码的情况下必填"
 }
 }
});

   

Html

密码<input id="password" name="password" type="password" />
确认密码<input id="confirm_password" name="confirm_password" type="password" />
条件验证<input id="funcvalidate" name="funcvalidate" value="" />

4、使用meta自定义验证信息

首先用JS设置meta

$("#form3").validate({ meta: "validate" });           

Html

email<input class="{validate:{required:true, email:true,
messages:{required:&#39;输入email地址&#39;, email:&#39;你输入的不是有效的邮件地址&#39;}}}"/>

   

5、使用meta可以将验证规则写在自定义的标签内,比如validate

JS设置meta

$().ready(function() {
 $.metadata.setType("attr", "validate");
 $("#form1").validate();
});

   

Html

Email

<input id="email" name="email" validate="{required:true, email:true, messages:{required:&#39;输入email地址&#39;, email:&#39;你输入的不是有效的邮件地址&#39;}}" />

6、自定义验证规则

对于复杂的验证,可以通过jQuery.validator.addMethod添加自定义的验证规则

官网提供的additional-methods.js里包含一些常用的验证方式,比如lettersonly,ziprange,nowhitespace等

例子

// 字符验证 
jQuery.validator.addMethod("userName", function(value, element) {
 return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value);
}, "用户名只能包括中文字、英文字母、数字和下划线"); 
 
//然后就可以使用这个规则了
$("#form1").validate({
 // 验证规则
 rules: {
 userName: {
  required: true,
  userName: true,
  rangelength: [5,10]
 }
 },
 /* 设置错误信息 */
 messages: {
 userName: {
  required: "请填写用户名",
  rangelength: "用户名必须在5-10个字符之间"
 }  
 },
});

7、radio、checkbox、select的验证方式类似

radio的验证

性别
<span>
 男<input type="radio" id="gender_male" value="m" name="gender" class="{required:true}"/><br />
 女<input type="radio" id="gender_female" value="f" name="gender" />
</span>

   

checkbox的验证

最少选择两项

<span>
 选项1<input type="checkbox" id="check_1" value="1" name="checkGroup"
 class="{required:true,minlength:2, messages:{required:&#39;必须选择&#39;,minlength:&#39;至少选择2项&#39;}}" /><br />
 选项2<input type="checkbox" id="check_2" value="2" name="checkGroup" /><br />
 选项3<input type="checkbox" id="check_3" value="3" name="checkGroup" /><br />
</span>

   

select的验证

下拉框

<span>
 <select id="selectbox" name="selectbox" class="{required:true}">
 <option value=""></option>
 <option value="1">1</option>
 <option value="2">2</option>
 <option value="3">3</option>
 </select>
</span>

   

8、Ajax验证

用remote可以进行Ajax验证

remote: {
url: "url", //url地址
type: "post",  //发送方式
dataType: "json", //数据格式 data: {   //要传递的数据
 username: function() {
 return $("#username").val();
 }}
}

   

验证用户多种信息: 

<script type="text/javascript"></script>
// 手机号码验证
jQuery.validator.addMethod("mobile", function(value, element) {
 var length = value.length;
 var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/
 return this.optional(element) || (length == 11 && mobile.test(value));
}, "手机号码格式错误");
 
// 电话号码验证
jQuery.validator.addMethod("phone", function(value, element) {
 var tel = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
 return this.optional(element) || (tel.test(value));
}, "电话号码格式错误");
 
// 邮政编码验证
jQuery.validator.addMethod("zipCode", function(value, element) {
 var tel = /^[0-9]{6}$/;
 return this.optional(element) || (tel.test(value));
}, "邮政编码格式错误");
 
// QQ号码验证
jQuery.validator.addMethod("qq", function(value, element) {
 var tel = /^[1-9]\d{4,9}$/;
 return this.optional(element) || (tel.test(value));
}, "qq号码格式错误");
 
// IP地址验证
jQuery.validator.addMethod("ip", function(value, element) {
 var ip = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
 return this.optional(element) || (ip.test(value) && (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256));
}, "Ip地址格式错误");
 
// 字母和数字的验证
jQuery.validator.addMethod("chrnum", function(value, element) {
 var chrnum = /^([a-zA-Z0-9]+)$/;
 return this.optional(element) || (chrnum.test(value));
}, "只能输入数字和字母(字符A-Z, a-z, 0-9)");
 
// 中文的验证
jQuery.validator.addMethod("chinese", function(value, element) {
 var chinese = /^[\u4e00-\u9fa5]+$/;
 return this.optional(element) || (chinese.test(value));
}, "只能输入中文");
 
// 下拉框验证
$.validator.addMethod("selectNone", function(value, element) {
 return value == "请选择";
}, "必须选择一项");
 
// 字节长度验证
jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {
 var length = value.length;
 for (var i = 0; i < value.length; i++) {
 if (value.charCodeAt(i) > 127) {
  length++;
 }
 }
 return this.optional(element) || (length >= param[0] && length <= param[1]);
}, $.validator.format("请确保输入的值在{0}-{1}个字节之间(一个中文字算2个字节)"));

    

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
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.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks 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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft