forked from nijikokun/Validator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator.js
260 lines (221 loc) · 8.04 KB
/
validator.js
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// Validator.js - v3.2
//
// JSON Schema Validator for API w/ a middleware for express
// Developed by Nijiko Yonskai <nijikokun@gmail.com>
// Copyright 2013
var Validator = function (schema, middleware) {
this.schema = schema;
this.parameters = Object.keys(this.schema);
this.errors = { };
this.retrieved = {};
this.debug = false;
if (middleware) return this.middleware;
};
Validator.index = function index(obj,is, value) {
if (typeof is == 'string')
return index(obj,is.split('.'), value);
else if (is.length==1 && value!==undefined)
return obj[is[0]] = value;
else if (is.length==0)
return obj;
else
return index(obj[is[0]],is.slice(1), value);
}
// Plugin System
Validator.plugins = {};
Validator.plugins._objects = [];
Validator.implement = function (field, isObject, callback) {
if (typeof isObject === 'function')
callback = isObject,
isObject = false;
if (isObject)
Validator.plugins._objects.push(field);
Validator.plugins[field] = function (details, key, data) {
var $this = this
, option = {
details: details,
field: field,
value: details[field],
key: key,
data: data,
error: function (type, message) {
if (typeof message === 'undefined')
message = type,
type = undefined;
$this.error(key, type || field, message, option);
return $this.errors;
}
};
callback.call(this, option);
return this.checkErrors();
};
};
// Validator Initialization Methods
Validator.prototype.middleware = function (req, res, next) {
this.against = req;
var results = this.validate();
if (results._error) return res.send(500, results);
else req.validated = results;
next();
};
Validator.prototype.check = function (against) {
this.against = against;
return this.validate();
};
// Parameter Check
//
// Retrieves data from either an express method, or explicitly given object.
Validator.prototype.param = function (key) {
if (this.against.param) return this.against.param(key);
return this.against[key];
};
// Roundup
//
// Gathers all sent data either through a request, or given explicitly,
// for fields that exist inside of the current schema.
Validator.prototype.roundup = function () {
var scheme;
return this.loop(function (key, data) {
if (scheme = this.schema[key]) {
if (data = this.param(key))
this.retrieved[key] = data;
else if (scheme.required && typeof scheme.default === 'undefined')
this.error(key, "required", "This parameter is required.");
else if (typeof scheme.default !== 'undefined')
this.retrieved[key] = scheme.default;
}
});
};
// Validation
Validator.prototype.validate = function () {
// Retrieve the data initially
// Check for errors after initial fetching.
if (this.roundup()) return this.errors;
// There has to be a better way to do nesting with default checks.
function loop (fields, details, key, data, deep) {
var i = 0, field;
fields.sort(function (a, b) {
return (a === 'required') ? 0 : 1;
});
for (i; i < fields.length; i++) {
if (field = fields[i].toLowerCase()) {
if (deep && field === 'required' || field === 'default') {
if (field === 'required' && typeof details.default === 'undefined' && !data) {
return this.error(key, "required", "This parameter is required.");
} else if (field === 'default' && typeof details.default !== 'undefined') {
Validator.index(this.retrieved, deep, details.default);
data = details.default;
}
continue;
}
if (Validator.plugins[field]) {
if (Validator.plugins[field].call(this, details, key, data))
return this.errors;
} else if (Object.prototype.toString.call(this.schema[key][field]) == "[object Object]" && Validator.plugins._objects.indexOf(field) == -1) {
if (loop.call(this, Object.keys(this.schema[key][field]), this.schema[key][field], field, this.retrieved[key][field], key + "." + field))
return this.errors;
}
}
}
}
// Loop through validations for each key
if (this.loop(function (key, data) {
var details = this.schema[key], fields = Object.keys(details);
return loop.call(this, fields, details, key, data);
})) return this.errors;
// Return retrieved data
return this.retrieved;
};
// Error Management
Validator.prototype.error = function (key, type, message, option) {
if (!this.errors._error) this.errors._error = true;
if (!this.errors[key]) this.errors[key] = {};
this.errors[key][type] = { message: message };
if (option && this.debug && typeof option.data !== "undefined")
this.errors[key][type].value = typeof option.data === 'object' ? JSON.stringify(option.data) : option.data;
};
Validator.prototype.checkErrors = function () {
return (Object.keys(this.errors).length > 0);
};
// Validation Looper
//
// Loops through the parameters in the schema, and gets the retrieved data which is then
// passed along to the given callback as `key` and `data` arguments.
Validator.prototype.loop = function (callback) {
var i = 0, key, data;
for (i; i < this.parameters.length; i++) {
key = this.parameters[i];
data = this.retrieved[key];
callback.call(this, key, data);
}
// Clear stored data
key = data = i = null;
// Check errors
return this.checkErrors();
};
// Validator Implementation
//
// Field: `type`
//
// Checks whether value is function to support using native words.
// Checks against `Object.prototype.toString.call` for exact type rather than `typeof`.
// By doing so it requires that the field starts with a capitol letter such as: `String`.
Validator.implement("type", function (options) {
if (typeof options.value === 'function')
options.value = options.value.name;
if (Object.prototype.toString.call(options.data) !== "[object " + options.value + "]")
options.error("Invalid parameter data type, expected: " + options.value);
});
// Validator Implementation
//
// Field: `length`
//
// Supports: `Number` or `Object` with `min` and `max` values.
//
// Checks given data length against a numerical value, when the field is an object we check against
// the `min` and `max` values. If the field is simply a numeric value we check for equality.
Validator.implement("length", true, function (options) {
if (typeof options.data === "undefined") return;
// Check whether length exists, otherwise use value
options.against = options.data.length ? options.data.length : options.data;
// Do Checks
if (typeof options.value === "object")
if (options.value.min)
if (options.value.min > options.against)
options.error("min", "Must be greater than " + options.value.min + (options.data.type === "string" ? " characters long." : ""));
if (options.value.max)
if (options.value.max < options.against)
options.error("max", "Must be less than " + options.value.max + (options.data.type === "string" ? " characters long." : ""));
else if (typeof options.value === "number")
if (options.value != options.against)
options.error("Must be " + options.value + " characters long.");
});
// Validator Implementation
//
// Field: `test`
//
// Supports: `RegExp` or `Array` of `RegExp`
//
// Checks given data against a single `RegExp` using `.test` or an `Array` of `RegExp` using `.test`
Validator.implement("test", function (options) {
if (Object.prototype.toString.call(options.value) === "[object Array]") {
var i = 0, regex;
for (i; i < options.value.length; i++) {
if (!options.value[i].test(options.data.toString()))
options.error("test-" + i, "Parameter data did not pass regex test.");
}
} else {
if (!options.value.test(options.data))
options.error("Parameter data did not pass regex test.");
}
});
// Export our module
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
module.exports = Validator;
else
if (typeof define === 'function' && define.amd)
define([], function() {
return Validator;
});
else
window.Validator = Validator;