这篇文章将为大家详细讲解有关jQuery如何实现validata插件,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
为了打LOL,我写快点,代码我都复制在最下面了,并且写了大量的注释。
首先我写jquery插件,喜欢这么写(好处有很多,以后在讲,哈哈,看过jQuery源码应该知道):
(function(root,factory,plug,undefined){
factory(root.jQuery,plug)
})(window,function($,plug){
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的div
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>
<div class="wrapper mt30">
<form action="##" class="member-forms" method="get">
<div class="mf-head rel tc">
<span class="f24">用户登录</span>
</div>
<div 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位字符之间" />
</div>
<div 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位" />
</div>
<input type="submit" class="mf-btn mt30" id="loginBtn" />
</form>
</div>
<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插件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。