Detailed explanation of jQuery validata plug-in example
本文主要为大家带来一篇jQuery validata插件实现方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。
首先我写jquery插件,喜欢这么写(好处有很多,以后在讲,哈哈,看过jQuery源码应该知道):
(function(root,factory,plug,undefined){ factory(root.jQuery,plug) })(window,function($,plug){ /*
在这里写逻辑
一:默认的参数 var __dEFAULTS__,
二:规则(可根据业务需求自己配置) var __RULES__,
三:原型 var __PROTOTYPE__,
_init: 初始化DOM结构,没什么将的,
_attachEvent: 自定义的事件的机制(其实就是用了jquery的trigger)
_bind: 首先是事件功能的绑定,为每一个input都绑定事件,each循环__RULES__(就是规则),找到所以自定义data的值(也就是每一个input中所需要的规则校验),用if来判断,当前的input中配置了几个data属性,并且通过 rule.call(_$field)(这句话的意思就是调用rule函数的时候,rule函数里的this引用变成了_$field),把input中的rule规则判断一下。如果为false,那么就在input的父元素下面添加一个p标签,那么怎么让p标签中的内容让用户来配置呢?
,这其中的意思是如果错了,那么就不往下检索rule了,直接return result(因为rule返回为false,所以这里的result也为false),来阻止。并且添加p标签,并且根据result的值来判断input的父元素,来个父元素加上一个success或error。最后还有submit方法:这个方法是用来通过input父元素的class中有没有error,来判断触发哪一个自定义事件四:$.fn[plug]
一:首先判断当前元素是否是from标签,不是的话,throw一个错误
二:$.extend(this,__dEFAULTS__,options,__PROTOTYPE__); (....貌似有同学面试死在这个上面了,有空讲一下吧)
三:this._init(); this._bind(); return this;
五:根据业务需求,用户自定义添加rule:就是如下添加一个方法,就可以了,(下次有时间还是讲一下extend吧)
$.fn[plug].extendRules = function(news){ $.extend(__RULES__,news); }
六:ajax
function login() { var username = $('#username').val(), password = $('#password').val(); var data = { "uname": username, "upwd": password }; $.ajax({ url: '/login', type: 'POST', data: data, success: function(data, status) { if (status == 'success') { location.href = 'home'; } }, error: function(data, status) { if (status == "error") { location.href = 'login' } } }); }
JS:
; (function(root, factory, plug, undefined) { factory(root.jQuery, plug); })(window, function($, plug) { //默认参数 var __dEFAULTS__ = { triggerEvent: "keyup", errorMessage: "You entered a wrong" }; /* require(需求) 必填项 regex(正则表达式)正则验证 length 长度验证 minlength 最短的长度 maxlength 最长的长度 between 两者之间的长度 equalto 和xxx相同 greaterThan 大于 lessThan 小于 middle 两者之间的数字 integer 整数 number 必须是数字 email 邮箱地址 mobile 电话号码 phone 手机号码 uri 有效的统一资源标识符 cardId 身份证号码 bankId 银行卡号码 ....其他的规则(根据业务规则来) */ var __RULES__ = { require: function() { return this.val() != ""; }, //(需求) 必填项 regex: function() { return new RegExp(this.data("regex")).test(this.val()); }, //(正则表达式)正则验证 length: function() { return this.val().length == Number(this.data("length")); }, // 长度验证 minlength: function() { return this.val().length >= Number(this.data("minlength")); }, // 最短的长度 maxlength: function() { return this.val().length <= Number(this.data("maxlength")); }, // 最长的长度 between: function() { var length = this.val().length; var between = this.data("between").split("-"); return length >= Number(between[0]) && length <= Number(between[1]); }, // 两者之间的长度 equalto: function() { if ($(this.data("equalto")).val() === this.val()) { $(this.data("equalto")).parent(".mf-line").removeClass('error').addClass('success').next("p").remove(); return true; } return false; }, // 和xxx相同 greaterthan: function() { return this.val() > Number(this.data("greaterthan")); }, // 大于 lessthan: function() { return this.val() < Number(this.data("lessthan")); }, // 小于 middle: function() { var length = this.val(); var middle = this.data("middle").split("-"); return length >= Number(middle[0]) && length <= Number(middle[1]); }, // 两者之间的数字 integer: function() { return /^\-?[0-9]*[1-9][0-9]*$/.test(this.val()); }, // 整数 number: function() { return !isNaN(Number(this.val())); }, // 必须是数字 email: function() { return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(this.val()); }, // 邮箱地址 mobile: function() { return /^1\d{10}$/.test(this.val()); }, // 电话号码 phone: function() { return /^\d{4}\-\d{8}$/.test(this.val()); }, // 手机号码 uri: function() { return /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g.test(this.val()); }, // 有效的统一资源标识符 amount: function() { //金额 if (!this.val()) return true; return /^([1-9][\d]{0,}|0)(\.[\d]{1,2})?$/.test(this.val()); } }; var __PROTOTYPE__ = { //初始化dom结构 _init: function() { this.$fields = this.find(".mf-line .mf-txt:visible"); //选择可见的input(过滤掉display: none) }, //自定义事件的触发机制 _attachEvent: function(event, args) { this.trigger(event, args); }, //事件 _bind: function() { var _$this = this; //事件功能绑定 this.$fields.on(this.triggerEvent, function() { var _$field = $(this); //需要验证的表单 var $group = _$field.parents(".mf-line"); //拿到input的p var result = true; $group.next("p").remove(); $.each(__RULES__, function(key, rule) { if (_$field.data(key)) { result = rule.call(_$field); (!result) && $group.after("<p class='message'>" + (_$field.data(key + "-message") || _$this.errorMessage) + "</p>"); return result; } }) $group.removeClass('error success').addClass(result ? 'success' : 'error'); }) this.on("submit", function() { var $groups = _$this.$fields.trigger(_$this.triggerEvent).parents(".mf-line"); if ($groups.filter(".error").length > 0) { _$this._attachEvent("error", {}); } else { _$this._attachEvent("success", {}); } return false; }) } } $.fn[plug] = function(options) { //判断this是否是form标签 if (!this.is("form")) { throw new Error("the trgger is not form tag"); } $.fn.extend(this, __dEFAULTS__, options, __PROTOTYPE__); this._init(); this._bind(); return this; } $.fn[plug].extendRules = function(news) { //根据业务需求增加rule $.extend(__RULES__, news); } }, "validator"); //这是调用插件的js $(function() { $.fn.validator.extendRules({ cardid: function() { return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(this.val()); } }) $(".member-forms").validator({ triggerEvent: "blur" }) .on("error", function(event, $errFiles) { return false; }) .on("success", function(event) { this.submit(); return false; }); });
HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>validata</title> <link rel="stylesheet" type="text/css" href="css/validata.css" rel="external nofollow" /> </head> <body> <p class="wrapper mt30"> <form action="##" class="member-forms" method="get"> <p class="mf-head rel tc"> <span class="f24">用户登录</span> </p> <p class="mf-line"> <span class="mf-name">帐号:</span> <input type="text" class="mf-txt" id="username" placeholder="请输入用户名/手机号" data-require="true" data-require-message="用户名必须填写" data-regex="^\w+$" data-regex-message="用户应该是由字母数字下划线所组成" data-between="6-12" data-between-message="用户名长度必须是在6-12位字符之间" /> </p> <p class="mf-line"> <span class="mf-name">密码:</span> <input type="password" class="mf-txt" id="password" placeholder="请输入密码" data-require="true" data-require-message="密码必须填写" data-regex="^[a-zA-Z0-9]+$" data-regex-message="密码应该是由字母数组所组成" data-minlength="8" data-minlength-message="密码长度最少8位" data-maxlength="12" data-maxlength-message="密码长度最多12位" /> </p> <input type="submit" class="mf-btn mt30" id="loginBtn" /> </form> </p> <script type="text/javascript" src="../jquery-2.2.4.js"></script> <script type="text/javascript" src="plug_in/validata.js"></script> <script type="text/javascript" src="js/index.js"></script> </body> </html>
css:
<style type="text/css"> body, html { width: 100%; height: 100%; font-family: "Microsoft yahei"; } * { margin: 0; padding: 0; } .tc { text-align: center; } .f24 { font-size: 24px; } .rel { position: relative; } .wrapper { max-width: 1186px; } .mt30 { margin-top: 30px; } .member-forms { max-width: 400px; margin: 20px auto; padding: 0 10px; background-color: #fff; } .member-forms .mf-line { margin-top: 30px; border: 1px solid #ddd; line-height: 52px; position: relative; padding-left: 110px; border-radius: 4px; } .member-forms .mf-line.error { border: 1px solid #a94442; } .member-forms .mf-line.success { border: 1px solid #3c763d; } .member-forms .mf-line .mf-name { position: absolute; left: 0; right: 0; text-align: center; width: 110px; } .member-forms .mf-line .mf-txt { display: block; height: 50px; width: 96%; border: 0px; padding: 0 2%; } .member-forms .message { width: 400px; font-size: 12px; color: red; } .member-forms .mf-btn { height: 52px; line-height: 52px; color: #fff; background-color: #5ba0e5; width: 100%; text-align: center; cursor: pointer; font-size: 18px; border: 0px; } </style>
相关推荐:
jquery.validata.js 插件集合,想要的都在这里
The above is the detailed content of Detailed explanation of jQuery validata plug-in example. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

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

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

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

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:

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

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
