jQuery/Zepto自定义插件

Posted by Nutlee on 2016-07-31

jQuery/Zepto 自定义插件,如下示例是一个表单验证插件,持续更新中….

                            

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
~function() {
var defaults = {
'rule': {},
'msg': {},
'msgstyle':{
'content': '<div class="error-msg">{{content}}</div>',
'parentclass': 'row-warn',
'errorclass':'error-msg'
}
};
var validateEachInput = function ($eachInput,name,validater,isShowValidateError) {
var $parent = $eachInput.parent(),
eachRule = validater['rule'][name],
eachMsg = validater['msg'][name],
msgstyle = validater.msgstyle,
isShowValidateError = isShowValidateError || false;
this.showMsg = function ($errorMsg,$parent,msgstyle,contnet) {
// console.log($errorMsg.length);
if ( !$errorMsg.length) {
var $parentHTML = $parent.html();
$parent.html($parentHTML + msgstyle.content.replace( /\{\{content\}\}/, contnet ));
} else {
$errorMsg.text('');
$errorMsg.text(contnet);
}
$parent.addClass(msgstyle.parentclass);
};
this.hideMsg = function ($errorMsg,$parent,msgstyle) {
if ($errorMsg.length) {
$parent.removeClass(msgstyle.parentclass);
}
};
// 是否必填
if (eachRule.required || false) {
var $errorMsg = $parent.find('.'+msgstyle['errorclass']);
if (!$eachInput.val().trim()) {
if ( isShowValidateError) {
showMsg($errorMsg,$parent,msgstyle,eachMsg.required);
};
return false;
} else {
if ( isShowValidateError) {
hideMsg($errorMsg,$parent,msgstyle);
};
}
};
//正则
if (eachRule.pattern || '') {
var $errorMsg = $parent.find('.'+msgstyle['errorclass']);
if (!eachRule.pattern.test($eachInput.val())) {
if ( isShowValidateError) {
showMsg($errorMsg,$parent,msgstyle,eachMsg.pattern);
};
return false;
} else {
if ( isShowValidateError) {
hideMsg($errorMsg,$parent,msgstyle);
}
}
};
return true;
};
$.fn.mValidation = function(options) {
var options = $.extend({}, defaults, options);
return this.each(function () {
var $that = $(this);
$.each(options.rule, function(index, val) {
validateEachInput($that.find('input[name='+index+']'),index,options,true);
});
});
};
}(Zepto);
$('#driverreg').mValidation({
'rule': {
'name': {
'required':true
},
'man_id': {
'required':true,
'pattern': /(^\d{15}$)|(^\d{17}([0-9]|X)$)/
}
},
'msg': {
'name': {
'required':'请输入您的姓名'
},
'man_id': {
'required':'请输入您的身份证号',
'pattern': '请输入正确的身份证号'
}
},
'msgstyle':{
'content': '<div class="error-msg">{{content}}</div>',
'parentclass': 'row-warn',
'errorclass':'error-msg'
}
});