-
Notifications
You must be signed in to change notification settings - Fork 82
/
revalidator.js
444 lines (396 loc) · 17.2 KB
/
revalidator.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
(function (exports) {
exports.validate = validate;
exports.mixin = mixin;
//
// ### function validate (object, schema, options)
// #### {Object} object the object to validate.
// #### {Object} schema (optional) the JSON Schema to validate against.
// #### {Object} options (optional) options controlling the validation
// process. See {@link #validate.defaults) for details.
// Validate <code>object</code> against a JSON Schema.
// If <code>object</code> is self-describing (i.e. has a
// <code>$schema</code> property), it will also be validated
// against the referenced schema. [TODO]: This behaviour bay be
// suppressed by setting the {@link #validate.options.???}
// option to <code>???</code>.[/TODO]
//
// If <code>schema</code> is not specified, and <code>object</code>
// is not self-describing, validation always passes.
//
// <strong>Note:</strong> in order to pass options but no schema,
// <code>schema</code> <em>must</em> be specified in the call to
// <code>validate()</code>; otherwise, <code>options</code> will
// be interpreted as the schema. <code>schema</code> may be passed
// as <code>null</code>, <code>undefinded</code>, or the empty object
// (<code>{}</code>) in this case.
//
function validate(object, schema, options) {
options = mixin({}, validate.defaults, options);
var errors = [];
if (schema.type === 'array')
validateProperty(object, object, '', schema, options, errors);
else
validateObject(object, schema, options, errors);
//
// TODO: self-described validation
// if (! options.selfDescribing) { ... }
//
return {
valid: !(errors.length),
errors: errors
};
};
/**
* Default validation options. Defaults can be overridden by
* passing an 'options' hash to {@link #validate}. They can
* also be set globally be changing the values in
* <code>validate.defaults</code> directly.
*/
validate.defaults = {
/**
* <p>
* Enforce 'format' constraints.
* </p><p>
* <em>Default: <code>true</code></em>
* </p>
*/
validateFormats: true,
/**
* <p>
* When {@link #validateFormats} is <code>true</code>,
* treat unrecognized formats as validation errors.
* </p><p>
* <em>Default: <code>false</code></em>
* </p>
*
* @see validation.formats for default supported formats.
*/
validateFormatsStrict: false,
/**
* <p>
* When {@link #validateFormats} is <code>true</code>,
* also validate formats defined in {@link #validate.formatExtensions}.
* </p><p>
* <em>Default: <code>true</code></em>
* </p>
*/
validateFormatExtensions: true,
/**
* <p>
* When {@link #additionalProperties} is <code>true</code>,
* allow additional unvisited properties on the object.
* </p><p>
* <em>Default: <code>true</code></em>
* </p>
*/
additionalProperties: true
};
/**
* Default messages to include with validation errors.
*/
validate.messages = {
required: "is required",
allowEmpty: "must not be empty",
minLength: "is too short (minimum is %{expected} characters)",
maxLength: "is too long (maximum is %{expected} characters)",
pattern: "invalid input",
minimum: "must be greater than or equal to %{expected}",
maximum: "must be less than or equal to %{expected}",
exclusiveMinimum: "must be greater than %{expected}",
exclusiveMaximum: "must be less than %{expected}",
divisibleBy: "must be divisible by %{expected}",
minItems: "must contain more than %{expected} items",
maxItems: "must contain less than %{expected} items",
uniqueItems: "must hold a unique set of values",
format: "is not a valid %{expected}",
conform: "must conform to given constraint",
type: "must be of %{expected} type",
additionalProperties: "must not exist"
};
validate.messages['enum'] = "must be present in given enumerator";
/**
*
*/
validate.formats = {
'email': /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
'ip-address': /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i,
'ipv6': /^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$/,
'date-time': /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:.\d{1,3})?Z$/,
'date': /^\d{4}-\d{2}-\d{2}$/,
'time': /^\d{2}:\d{2}:\d{2}$/,
'color': /^#[a-z0-9]{6}|#[a-z0-9]{3}|(?:rgb\(\s*(?:[+-]?\d+%?)\s*,\s*(?:[+-]?\d+%?)\s*,\s*(?:[+-]?\d+%?)\s*\))aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow$/i,
//'style': (not supported)
//'phone': (not supported)
//'uri': (not supported)
'host-name': /^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])/,
'utc-millisec': {
test: function (value) {
return typeof(value) === 'number' && value >= 0;
}
},
'regex': {
test: function (value) {
try { new RegExp(value) }
catch (e) { return false }
return true;
}
}
};
/**
*
*/
validate.formatExtensions = {
'url': /^(https?|ftp|git):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i
};
function mixin(obj) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue }
if (typeof(source) !== 'object') {
throw new TypeError('mixin non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
}
function validateObject(object, schema, options, errors) {
var props, allProps = Object.keys(object),
visitedProps = [];
// see 5.2
if (schema.properties) {
props = schema.properties;
for (var p in props) {
if (props.hasOwnProperty(p)) {
visitedProps.push(p);
validateProperty(object, object[p], p, props[p], options, errors);
}
}
}
// see 5.3
if (schema.patternProperties) {
props = schema.patternProperties;
for (var p in props) {
if (props.hasOwnProperty(p)) {
var re = new RegExp(p);
// Find all object properties that are matching `re`
for (var k in object) {
if (object.hasOwnProperty(k)) {
if (re.exec(k) !== null) {
validateProperty(object, object[k], k, props[p], options, errors);
visitedProps.push(k);
}
}
}
}
}
}
//if additionalProperties is not defined set default value
if (schema.additionalProperties === undefined) {
schema.additionalProperties = options.additionalProperties;
}
// see 5.4
if (undefined !== schema.additionalProperties) {
var i, l;
var unvisitedProps = allProps.filter(function(k){
return -1 === visitedProps.indexOf(k);
});
// Prevent additional properties; each unvisited property is therefore an error
if (schema.additionalProperties === false && unvisitedProps.length > 0) {
for (i = 0, l = unvisitedProps.length; i < l; i++) {
error("additionalProperties", unvisitedProps[i], object[unvisitedProps[i]], false, errors);
}
}
// additionalProperties is a schema and validate unvisited properties against that schema
else if (typeof schema.additionalProperties == "object" && unvisitedProps.length > 0) {
for (i = 0, l = unvisitedProps.length; i < l; i++) {
validateProperty(object, object[unvisitedProps[i]], unvisitedProps[i], schema.unvisitedProperties, options, errors);
}
}
}
}
function validateProperty(object, value, property, schema, options, errors) {
var format,
valid,
spec,
type;
function constrain(name, value, assert) {
if (schema[name] !== undefined && !assert(value, schema[name])) {
error(name, property, value, schema, errors);
}
}
if (value === undefined) {
if (schema.required && schema.type !== 'any') {
return error('required', property, undefined, schema, errors);
} else {
return;
}
}
if (options.cast) {
if (('integer' === schema.type || 'number' === schema.type) && value == +value) {
value = +value;
object[property] = value;
}
if ('boolean' === schema.type) {
if ('true' === value || '1' === value || 1 === value) {
value = true;
object[property] = value;
}
if ('false' === value || '0' === value || 0 === value) {
value = false;
object[property] = value;
}
}
}
if (schema.format && options.validateFormats) {
format = schema.format;
if (options.validateFormatExtensions) { spec = validate.formatExtensions[format] }
if (!spec) { spec = validate.formats[format] }
if (!spec) {
if (options.validateFormatsStrict) {
return error('format', property, value, schema, errors);
}
}
else {
if (!spec.test(value)) {
return error('format', property, value, schema, errors);
}
}
}
if (schema['enum'] && schema['enum'].indexOf(value) === -1) {
error('enum', property, value, schema, errors);
}
// Dependencies (see 5.8)
if (typeof schema.dependencies === 'string' &&
object[schema.dependencies] === undefined) {
error('dependencies', property, null, schema, errors);
}
if (isArray(schema.dependencies)) {
for (var i = 0, l = schema.dependencies.length; i < l; i++) {
if (object[schema.dependencies[i]] === undefined) {
error('dependencies', property, null, schema, errors);
}
}
}
if (typeof schema.dependencies === 'object') {
validateObject(object, schema.dependencies, options, errors);
}
checkType(value, schema.type, function(err, type) {
if (err) return error('type', property, typeof value, schema, errors);
constrain('conform', value, function (a, e) { return e(a, object) });
switch (type || (isArray(value) ? 'array' : typeof value)) {
case 'string':
constrain('allowEmpty', value, function (a, e) { return e ? e : a !== '' });
constrain('minLength', value.length, function (a, e) { return a >= e });
constrain('maxLength', value.length, function (a, e) { return a <= e });
constrain('pattern', value, function (a, e) {
e = typeof e === 'string'
? e = new RegExp(e)
: e;
return e.test(a)
});
break;
case 'integer':
case 'number':
constrain('minimum', value, function (a, e) { return a >= e });
constrain('maximum', value, function (a, e) { return a <= e });
constrain('exclusiveMinimum', value, function (a, e) { return a > e });
constrain('exclusiveMaximum', value, function (a, e) { return a < e });
constrain('divisibleBy', value, function (a, e) {
var multiplier = Math.max((a - Math.floor(a)).toString().length - 2, (e - Math.floor(e)).toString().length - 2);
multiplier = multiplier > 0 ? Math.pow(10, multiplier) : 1;
return (a * multiplier) % (e * multiplier) === 0
});
break;
case 'array':
constrain('items', value, function (a, e) {
var nestedErrors;
for (var i = 0, l = a.length; i < l; i++) {
nestedErrors = [];
validateProperty(object, a[i], property, e, options, nestedErrors);
nestedErrors.forEach(function (err) {
err.property =
(property ? property + '.' : '') +
i +
(err.property ? '.' + err.property.replace(property + '.', '') : '');
});
nestedErrors.unshift(0, 0);
Array.prototype.splice.apply(errors, nestedErrors);
}
return true;
});
constrain('minItems', value, function (a, e) { return a.length >= e });
constrain('maxItems', value, function (a, e) { return a.length <= e });
constrain('uniqueItems', value, function (a, e) {
if (!e) return true;
var h = {};
for (var i = 0, l = a.length; i < l; i++) {
var key = JSON.stringify(a[i]);
if (h[key]) return false;
h[key] = true;
}
return true;
});
break;
case 'object':
// Recursive validation
if (schema.properties || schema.patternProperties || schema.additionalProperties) {
var nestedErrors = [];
validateObject(value, schema, options, nestedErrors);
nestedErrors.forEach(function (e) {
e.property = property + '.' + e.property
});
nestedErrors.unshift(0, 0);
Array.prototype.splice.apply(errors, nestedErrors);
}
break;
}
});
}
function checkType(val, type, callback) {
var result = false,
types = isArray(type) ? type : [type];
// No type - no check
if (type === undefined) return callback(null, type);
// Go through available types
// And fine first matching
for (var i = 0, l = types.length; i < l; i++) {
type = types[i].toLowerCase().trim();
if (type === 'string' ? typeof val === 'string' :
type === 'array' ? isArray(val) :
type === 'object' ? val && typeof val === 'object' &&
!isArray(val) :
type === 'number' ? typeof val === 'number' :
type === 'integer' ? typeof val === 'number' && Math.floor(val) === val :
type === 'null' ? val === null :
type === 'boolean'? typeof val === 'boolean' :
type === 'date' ? isDate(val) :
type === 'any' ? typeof val !== 'undefined' : false) {
return callback(null, type);
}
}
callback(true);
}
function error(attribute, property, actual, schema, errors) {
var lookup = { expected: schema[attribute], actual: actual, attribute: attribute, property: property };
var message = schema.messages && schema.messages[attribute] || schema.message || validate.messages[attribute] || "no default message";
message = message.replace(/%\{([a-z]+)\}/ig, function (_, match) { return lookup[match.toLowerCase()] || ''; });
errors.push({
attribute: attribute,
property: property,
expected: schema[attribute],
actual: actual,
message: message
});
}
function isArray(value) {
return Object.prototype.toString.call(value) === '[object Array]';
}
function isDate(value) {
return Object.prototype.toString.call(value) === '[object Date]';
}
})(typeof module === 'object' && module && module.exports ? module.exports : window);