


Simple example demonstration of jquery implementation of form validation_jquery
The example in this article describes the jquery implementation of form validation code. Share it with everyone for your reference. The details are as follows:
The screenshot of the running effect is as follows:
The specific code is as follows:
It’s easier to go directly to the plug-in to implement the code. It’s easier to explain around the code:
/* 描述:基于jquery的表单验证插件。 */ (function ($) { $.fn.checkForm = function (options) { var root = this; //将当前应用对象存入root var isok = false; //控制表单提交的开关 var pwd1; //密码存储 var defaults = { //图片路径 img_error: "img/error.gif", img_success: "img/success.gif", //提示信息 tips_success: '', //验证成功时的提示信息,默认为空 tips_required: '不能为空', tips_email: '邮箱地址格式有误', tips_num: '请填写数字', tips_chinese: '请填写中文', tips_mobile: '手机号码格式有误', tips_idcard: '身份证号码格式有误', tips_pwdequal: '两次密码不一致', //正则 reg_email: /^\w+\@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/i, //验证邮箱 reg_num: /^\d+$/, //验证数字 reg_chinese: /^[\u4E00-\u9FA5]+$/, //验证中文 reg_mobile: /^1[3458]{1}[0-9]{9}$/, //验证手机 reg_idcard: /^\d{14}\d{3}?\w$/ //验证身份证 }; //不为空则合并参数 if(options) $.extend(defaults, options); //获取(文本框,密码框,多行文本框),当失去焦点时,对其进行数据验证 $(":text,:password,textarea", root).each(function () { $(this).blur(function () { var _validate = $(this).attr("check"); //获取check属性的值 if (_validate) { var arr = _validate.split(' '); //用空格将其拆分成数组 for (var i = 0; i < arr.length; i++) { //逐个进行验证,不通过跳出返回false,通过则继续 if (!check($(this), arr[i], $(this).val())) return false; else continue; } } }) }) //表单提交时执行验证,与上面的方法基本相同,只不过是在表单提交时触发 function _onSubmit() { isok = true; $(":text,:password,textarea", root).each(function () { var _validate = $(this).attr("check"); if (_validate) { var arr = _validate.split(' '); for (var i = 0; i < arr.length; i++) { if (!check($(this), arr[i], $(this).val())) { isok = false; //验证不通过阻止表单提交,开关false return; //跳出 } } } }); } //判断当前对象是否为表单,如果是表单,则提交时要进行验证 if (root.is("form")) { root.submit(function () { _onSubmit(); return isok; }) } //验证方法 var check = function (obj, _match, _val) { //根据验证情况,显示相应提示信息,返回相应的值 switch (_match) { case 'required': return _val ? showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_required, false); case 'email': return chk(_val, defaults.reg_email) ? showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_email, false); case 'num': return chk(_val, defaults.reg_num) ? showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_num, false); case 'chinese': return chk(_val, defaults.reg_chinese) ? showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_chinese, false); case 'mobile': return chk(_val, defaults.reg_mobile) ? showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_mobile, false); case 'idcard': return chk(_val, defaults.reg_idcard) ? showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_idcard, false); case 'pwd1': pwd1 = _val; //实时获取存储pwd1值 return true; case 'pwd2': return pwdEqual(_val, pwd1) ? showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_pwdequal, false); default: return true; } } //判断两次密码是否一致(返回bool值) var pwdEqual = function(val1, val2) { return val1 == val2 ? true : false; } //正则匹配(返回bool值) var chk = function (str, reg) { return reg.test(str); } //显示信息 var showMsg = function (obj, msg, mark) { $(obj).next("#errormsg").remove();//先清除 var _html = "<span id='errormsg' style='font-size:13px;color:gray;background:url(" + defaults.img_error + ") no-repeat 0 -1px;padding-left:20px;margin-left:5px;'>" + msg + "</span>"; if (mark) _html = "<span id='errormsg' style='font-size:13px;color:gray;background:url(" + defaults.img_success + ") no-repeat 0 -1px;padding-left:20px;margin-left:5px;'>" + msg + "</span>"; $(obj).after(_html);//再添加 return mark; } } })(jQuery);
Let’s talk about the implementation principle first:
First define the regular rules and the corresponding prompt information,
Add custom check attribute,
Then get the value of the check attribute, and separate multiple values with spaces. Use split() to split it into an array, and call the check() method one by one to verify.
Then the displayed information is determined by the return value of the verification.
There are two special verifications here, namely:
1. Verify whether it is empty (required)
2. Are the two passwords consistent (pwd2)
Neither of these two uses regular expressions, because they are not used at all. Whether the two passwords are consistent, I wrote a separate method pwdEqual();
I have only written a few verification rules in the plug-in. If they are not enough, you can expand and add them by yourself.
Extension only takes 3 steps:
1. Add regular expression,
2. Add corresponding prompt information,
3. Add corresponding case processing in the check() method
Instructions for using the plug-in:
1. Add custom check attributes to the text boxes, password boxes, and multi-line text boxes that need to be verified in the form
2. Multiple format verifications are separated by spaces, such as (verifying required fields and email at the same time): check="required email"
3. If you want to verify whether the two passwords are consistent, use pwd1 and pwd2 together, as shown below:
pwd1 stores the value entered for the first time, and pwd2 stores the value entered for the second time. It’s okay if you only use pwd1, but if you only use pwd2, the verification will never pass.
DEMO sample code is given below:
<!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>表单验证插件</title> </head> <body> <form id="myform" method="post" action="success.html"> <ul> <li> 邮箱:<input type="text" name="email" check="required email" /> </li> <li> 密码:<input type="password" check="required pwd1" /> </li> <li> 确认密码:<input type="password" check="required pwd2" /> </li> <li> 手机:<input type="text" name="num" check="required mobile" /> </li> <li> 数字:<input type="text" name="num" check="required num" /> </li> <li> 地址:<textarea cols="5" rows="5" check="required"></textarea> </li> <li> 不加check验证的文本框:<input type="text" name="num" /> </li> </ul> <input type="submit" value="提交" /> </form> <script src="js/jquery-1.4.4.min.js" type="text/javascript"></script> <script src="js/jquery.similar.checkForm.js" type="text/javascript"></script> <script type="text/javascript"> $("#myform").checkForm(); </script> </body> </html>
Sample effect picture:
If the sample code is successfully submitted, it will jump to the success.html page, so you need to create a success.html yourself. You can write nothing in it.
However, as long as one verification fails, the jump will not be successful.
In addition, you may also need 2 pictures:
//Picture path
img_error: "img/error.gif",
img_success: "img/success.gif",
Uploaded here, right click and save as.
The above is the entire content of this article. I hope it can help everyone find a better way to master the implementation of jquery verification code.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s
