-
Notifications
You must be signed in to change notification settings - Fork 0
/
revalidator.js
362 lines (322 loc) · 13.8 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
(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({}, options, validate.defaults);
var errors = [];
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
};
/**
* Default messages to include with validation errors.
*/
validate.messages = {
required: "is required",
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}"
};
/**
*
*/
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|and yellow$/i,
//'style': (not supported)
//'phone': (not supported)
//'uri': (not supported)
//'host-name': (not supported)
'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;
// see 5.2
if (schema.properties) {
props = schema.properties;
for (var p in props) {
if (props.hasOwnProperty(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) && re.exec(k) !== null) {
validateProperty(object, object[k], p, props[p], 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 (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) });
switch (type || (isArray(value) ? 'array' : typeof value)) {
case 'string':
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 '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) {
for (var i = 0, l = a.length; i < l; i++) {
validateProperty(object, a[i], property, e, options, errors);
}
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) {
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) {
validateObject(value, schema, options, errors);
}
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];
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' && ~~val === val :
type === 'null' ? val === null :
type === 'boolean'? typeof val === 'boolean' :
type === 'any' ? typeof val !== 'undefined' : false) {
return callback(null, type);
}
};
callback(true);
};
function error(attribute, property, actual, schema, errors) {
var lookup = { expected: schema[attribute], attribute: attribute, property: property };
var message = schema.messages && schema.messages[attribute] || 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) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (typeof value.length === 'number' &&
!(value.propertyIsEnumerable('length')) &&
typeof value.splice === 'function') {
return true;
}
}
}
return false;
}
})(typeof(window) === 'undefined' ? module.exports : (window.json = window.json || {}));