validate.js
2.44 KB
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
99
100
var _isInput = function(element) {
if (!element || !element.tagName) {
return false;
}
var tagName = element.tagName.toLowerCase();
return tagName === 'input' || tagName === 'textarea';
};
var _extend = function(out) {
out = out || {};
for (var i = 1; i < arguments.length; i++) {
var obj = arguments[i];
if (!obj)
continue;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object')
out[key] = _extend(out[key], obj[key]);
else
out[key] = obj[key];
}
}
}
return out;
};
var regExps = {
email: /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i,
url: /^((https?):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,
numbers: /^\d+(\.\d{1,2})?$/,
digits: /^[0-9]*$/,
letters: /[a-z][A-Z]*$/
};
var Validate = function(element, options) {
if (!_isInput(element)) {
throw new Error('控件不存在');
}
if (!options.rules || Object.keys(options.rules).length === 0) {
throw new Error('规则不存在');
}
var defaults = {
regExps: regExps,
messages: "messages"
};
this.options = _extend({}, defaults, options);
this.element = element;
this.regExps = regExps;
};
var fn = Validate.prototype;
fn.validate = function(onError) {
var isValid = true;
this.value = this.element.value;
for (var rule in this.options.rules) {
var test = this[rule];
if (!test || typeof test !== 'function') {
throw new Error(rule);
}
var param = this.options.rules[rule];
if (!this[rule](param)) {
isValid = false;
this.message = "Error"//_createMessage(this.options.messages[rule], {rule: param, data: this.value});
onError&&onError.call(null,this);
break;
}
}
if (isValid) {
return true;
}
};
fn.required = function() {
return this.value.trim().length > 0;
};
fn.min = function(param) {
return this.value.length >= param;
};
fn.max = function(param) {
return this.value.length <= param;
};
fn.match = function(param) {
var re = this.regExps[param];
if (!re) {
var regrex=new RegExp(param,'g')
return regrex.test(this.value);
//throw new Error(param + ':'
// + Object.keys(this.options.regExps).join(', '));
}
return this.regExps[param].test(this.value);
};
module.exports={
init: Validate,
fn: fn
};;