-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathvalidator.js
More file actions
137 lines (104 loc) · 2.93 KB
/
validator.js
File metadata and controls
137 lines (104 loc) · 2.93 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
var V = (function ($) {
var validator = {
// Can add to this, eg a telephone validator
type: {
'noCheck': {
ok: function () { return true; }
},
'required': {
ok: function (value) {
var emptyString = $.type(value) === 'string' && $.trim(value) === '';
return value !== undefined && value !== null && !emptyString;
},
message: 'This field is required'
},
'email': {
ok: function (value) {
var re = /[a-z0-9_]+@[a-z0-9_]+\.[a-z]{3}/i;
return re.test(value);
},
message: 'Invalid Email'
}
},
/**
*
* @param config
* {
* '<jquery-selector>': string | object | [ string ]
* }
*/
validate: function (config) {
// 1. Normalize the configuration object
config = normalizeConfig(config);
var promises = [],
checks = [];
// 2. Convert each validation to a promise
$.each(config, function (idx, v) {
var value = v.control.val();
var retVal = v.check.ok(value);
// Make a promise, check is based on Promises/A+ spec
if (retVal.then) {
promises.push(retVal);
}
else {
var p = $.Deferred();
if (retVal) p.resolve();
else p.reject();
promises.push(p.promise());
}
checks.push(v);
});
// 3. Wrap into a master promise
var masterPromise = $.Deferred();
$.when.apply(null, promises)
.done(function () {
masterPromise.resolve();
})
.fail(function () {
var failed = [];
$.each(promises, function (idx, x) {
if (x.state() === 'rejected') {
var failedCheck = checks[idx];
var error = {
check: failedCheck.checkName,
error: failedCheck.check.message,
field: failedCheck.field,
control: failedCheck.control
};
failed.push(error);
}
});
masterPromise.reject(failed);
});
// 4. Return the master promise
return masterPromise.promise();
}
};
/**
*
* @param config
* @returns {Array}
*/
function normalizeConfig(config) {
config = config || {};
var validations = [];
$.each(config, function (selector, obj) {
// make an array for simplified checking
var checks = $.isArray(obj.checks) ? obj.checks : [obj.checks];
$.each(checks, function (idx, check) {
validations.push({
control: $(selector),
check: getValidator(check),
checkName: check,
field: obj.field
});
});
});
return validations;
}
function getValidator(type) {
if ($.type(type) === 'string' && validator.type[type]) return validator.type[type];
return validator.noCheck;
}
return validator;
})(jQuery);