1 | # Tiny Validator (for v4 JSON Schema) |
---|
2 | |
---|
3 | [](http://travis-ci.org/geraintluff/tv4) [](https://gemnasium.com/geraintluff/tv4) [](http://badge.fury.io/js/tv4) |
---|
4 | |
---|
5 | Use [json-schema](http://json-schema.org/) [draft v4](http://json-schema.org/latest/json-schema-core.html) to validate simple values and complex objects using a rich [validation vocabulary](http://json-schema.org/latest/json-schema-validation.html) ([examples](http://json-schema.org/examples.html)). |
---|
6 | |
---|
7 | There is support for `$ref` with JSON Pointer fragment paths (```other-schema.json#/properties/myKey```). |
---|
8 | |
---|
9 | ## Usage 1: Simple validation |
---|
10 | |
---|
11 | ```javascript |
---|
12 | var valid = tv4.validate(data, schema); |
---|
13 | ``` |
---|
14 | |
---|
15 | If validation returns ```false```, then an explanation of why validation failed can be found in ```tv4.error```. |
---|
16 | |
---|
17 | The error object will look something like: |
---|
18 | ```json |
---|
19 | { |
---|
20 | "code": 0, |
---|
21 | "message": "Invalid type: string", |
---|
22 | "dataPath": "/intKey", |
---|
23 | "schemaKey": "/properties/intKey/type" |
---|
24 | } |
---|
25 | ``` |
---|
26 | |
---|
27 | The `"code"` property will refer to one of the values in `tv4.errorCodes` - in this case, `tv4.errorCodes.INVALID_TYPE`. |
---|
28 | |
---|
29 | To enable external schema to be referenced, you use: |
---|
30 | ```javascript |
---|
31 | tv4.addSchema(url, schema); |
---|
32 | ``` |
---|
33 | |
---|
34 | If schemas are referenced (```$ref```) but not known, then validation will return ```true``` and the missing schema(s) will be listed in ```tv4.missing```. For more info see the API documentation below. |
---|
35 | |
---|
36 | ## Usage 2: Multi-threaded validation |
---|
37 | |
---|
38 | Storing the error and missing schemas does not work well in multi-threaded environments, so there is an alternative syntax: |
---|
39 | |
---|
40 | ```javascript |
---|
41 | var result = tv4.validateResult(data, schema); |
---|
42 | ``` |
---|
43 | |
---|
44 | The result will look something like: |
---|
45 | ```json |
---|
46 | { |
---|
47 | "valid": false, |
---|
48 | "error": {...}, |
---|
49 | "missing": [...] |
---|
50 | } |
---|
51 | ``` |
---|
52 | |
---|
53 | ## Usage 3: Multiple errors |
---|
54 | |
---|
55 | Normally, `tv4` stops when it encounters the first validation error. However, you can collect an array of validation errors using: |
---|
56 | |
---|
57 | ```javascript |
---|
58 | var result = tv4.validateMultiple(data, schema); |
---|
59 | ``` |
---|
60 | |
---|
61 | The result will look something like: |
---|
62 | ```json |
---|
63 | { |
---|
64 | "valid": false, |
---|
65 | "errors": [ |
---|
66 | {...}, |
---|
67 | ... |
---|
68 | ], |
---|
69 | "missing": [...] |
---|
70 | } |
---|
71 | ``` |
---|
72 | |
---|
73 | ## Asynchronous validation |
---|
74 | |
---|
75 | Support for asynchronous validation (where missing schemas are fetched) can be added by including an extra JavaScript file. Currently, the only version requires jQuery (`tv4.async-jquery.js`), but the code is very short and should be fairly easy to modify for other libraries (such as MooTools). |
---|
76 | |
---|
77 | Usage: |
---|
78 | |
---|
79 | ```javascript |
---|
80 | tv4.validate(data, schema, function (isValid, validationError) { ... }); |
---|
81 | ``` |
---|
82 | |
---|
83 | `validationFailure` is simply taken from `tv4.error`. |
---|
84 | |
---|
85 | ## Cyclical JavaScript objects |
---|
86 | |
---|
87 | While they don't occur in proper JSON, JavaScript does support self-referencing objects. Any of the above calls support an optional final argument, checkRecursive. If true, tv4 will handle self-referencing objects properly - this slows down validation slightly, but that's better than a hanging script. |
---|
88 | |
---|
89 | Consider this data, notice how both `a` and `b` refer to each other: |
---|
90 | |
---|
91 | ```javascript |
---|
92 | var a = {}; |
---|
93 | var b = { a: a }; |
---|
94 | a.b = b; |
---|
95 | var aSchema = { properties: { b: { $ref: 'bSchema' }}}; |
---|
96 | var bSchema = { properties: { a: { $ref: 'aSchema' }}}; |
---|
97 | tv4.addSchema('aSchema', aSchema); |
---|
98 | tv4.addSchema('bSchema', bSchema); |
---|
99 | ``` |
---|
100 | |
---|
101 | If the final checkRecursive argument were missing, this would throw a "too much recursion" error. |
---|
102 | |
---|
103 | To enable supprot for this pass `true` as additional argument to any of the regular validation methods: |
---|
104 | |
---|
105 | ```javascript |
---|
106 | tv4.validate(a, aSchema, true); |
---|
107 | tv4.validate(a, schema, asynchronousFunction, true); |
---|
108 | |
---|
109 | tv4.validateResult(data, aSchema, true); |
---|
110 | tv4.validateMultiple(data, aSchema, true); |
---|
111 | ``` |
---|
112 | |
---|
113 | ## API |
---|
114 | |
---|
115 | There are additional api commands available for more complex use-cases: |
---|
116 | |
---|
117 | ##### addSchema(uri, schema) |
---|
118 | Pre-register a schema for reference by other schema and synchronous validation. |
---|
119 | |
---|
120 | ````js |
---|
121 | tv4.addSchema('http://example.com/schema', { ... }); |
---|
122 | ```` |
---|
123 | |
---|
124 | * `uri` the uri to identify this schema. |
---|
125 | * `schema` the schema object. |
---|
126 | |
---|
127 | Schemas that have their `id` property set can be added directly. |
---|
128 | |
---|
129 | ````js |
---|
130 | tv4.addSchema({ ... }); |
---|
131 | ```` |
---|
132 | |
---|
133 | ##### getSchema(uri) |
---|
134 | |
---|
135 | Return a schema from the cache. |
---|
136 | |
---|
137 | * `uri` the uri of the schema (may contain a `#` fragment) |
---|
138 | |
---|
139 | ````js |
---|
140 | var schema = tv4.getSchema('http://example.com/schema'); |
---|
141 | ```` |
---|
142 | |
---|
143 | ##### getSchemaMap() |
---|
144 | |
---|
145 | Return a shallow copy of the schema cache, mapping schema document URIs to schema objects. |
---|
146 | |
---|
147 | ```` |
---|
148 | var map = tv4.getSchemaMap(); |
---|
149 | |
---|
150 | var schema = map[uri]; |
---|
151 | ```` |
---|
152 | |
---|
153 | ##### getSchemaUris(filter) |
---|
154 | |
---|
155 | Return an Array with known schema document URIs. |
---|
156 | |
---|
157 | * `filter` optional RegExp to filter URIs |
---|
158 | |
---|
159 | ```` |
---|
160 | var arr = tv4.getSchemaUris(); |
---|
161 | |
---|
162 | // optional filter using a RegExp |
---|
163 | var arr = tv4.getSchemaUris(/^https?://example.com/); |
---|
164 | ```` |
---|
165 | |
---|
166 | ##### getMissingUris(filter) |
---|
167 | |
---|
168 | Return an Array with schema document URIs that are used as `$ref` in known schemas but which currently have no associated schema data. |
---|
169 | |
---|
170 | Use this in combination with `tv4.addSchema(uri, schema)` to preload the cache for complete synchronous validation with. |
---|
171 | |
---|
172 | * `filter` optional RegExp to filter URIs |
---|
173 | |
---|
174 | ```` |
---|
175 | var arr = tv4.getMissingUris(); |
---|
176 | |
---|
177 | // optional filter using a RegExp |
---|
178 | var arr = tv4.getMissingUris(/^https?://example.com/); |
---|
179 | ```` |
---|
180 | |
---|
181 | ##### dropSchemas() |
---|
182 | |
---|
183 | Drop all known schema document URIs from the cache. |
---|
184 | |
---|
185 | ```` |
---|
186 | tv4.dropSchemas(); |
---|
187 | ```` |
---|
188 | |
---|
189 | ##### freshApi() |
---|
190 | |
---|
191 | Return a new tv4 instance with no shared state. |
---|
192 | |
---|
193 | ```` |
---|
194 | var otherTV4 = tv4.freshApi(); |
---|
195 | ```` |
---|
196 | |
---|
197 | ##### reset() |
---|
198 | |
---|
199 | Manually reset validation status from the simple `tv4.validate(data, schema)`. Although tv4 will self reset on each validation there are some implementation scenarios where this is useful. |
---|
200 | |
---|
201 | ```` |
---|
202 | tv4.reset(); |
---|
203 | ```` |
---|
204 | |
---|
205 | ##### language(code) |
---|
206 | |
---|
207 | Select the language map used for reporting. |
---|
208 | |
---|
209 | * `code` is a language code, like `'en'` or `'en-gb'` |
---|
210 | |
---|
211 | ```` |
---|
212 | tv4.language('en-gb'); |
---|
213 | ```` |
---|
214 | |
---|
215 | ##### addLanguage(code, map) |
---|
216 | |
---|
217 | Add a new language map for selection by `tv4.language(code)` |
---|
218 | |
---|
219 | * `code` is new language code |
---|
220 | * `map` is an object mapping error IDs or constant names (e.g. `103` or `"NUMBER_MAXIMUM"`) to language strings. |
---|
221 | |
---|
222 | ```` |
---|
223 | tv4.addLanguage('fr', { ... }); |
---|
224 | |
---|
225 | // select for use |
---|
226 | tv4.language('fr') |
---|
227 | ```` |
---|
228 | |
---|
229 | ##### addFormat(format, validationFunction) |
---|
230 | |
---|
231 | Add a custom format validator. |
---|
232 | |
---|
233 | * `format` is a string, corresponding to the `"format"` value in schemas. |
---|
234 | * `validationFunction` is a function that either returns: |
---|
235 | * `null` (meaning no error) |
---|
236 | * an error string (explaining the reason for failure) |
---|
237 | |
---|
238 | ```` |
---|
239 | tv4.addFormat('decimal-digits', function (data, schema) { |
---|
240 | if (typeof data === 'string' && !/^[0-9]+$/.test(data)) { |
---|
241 | return null; |
---|
242 | } |
---|
243 | return "must be string of decimal digits"; |
---|
244 | }); |
---|
245 | ```` |
---|
246 | |
---|
247 | Alternatively, multiple formats can be added at the same time using an object: |
---|
248 | ```` |
---|
249 | tv4.addFormat({ |
---|
250 | 'my-format': function () {...}, |
---|
251 | 'other-format': function () {...} |
---|
252 | }); |
---|
253 | ```` |
---|
254 | |
---|
255 | ## Demos |
---|
256 | |
---|
257 | ### Basic usage |
---|
258 | <div class="content inline-demo" markdown="1" data-demo="demo1"> |
---|
259 | <pre class="code" id="demo1"> |
---|
260 | var schema = { |
---|
261 | "items": { |
---|
262 | "type": "boolean" |
---|
263 | } |
---|
264 | }; |
---|
265 | var data1 = [true, false]; |
---|
266 | var data2 = [true, 123]; |
---|
267 | |
---|
268 | alert("data 1: " + tv4.validate(data1, schema)); // true |
---|
269 | alert("data 2: " + tv4.validate(data2, schema)); // false |
---|
270 | alert("data 2 error: " + JSON.stringify(tv4.error, null, 4)); |
---|
271 | </pre> |
---|
272 | </div> |
---|
273 | |
---|
274 | ### Use of <code>$ref</code> |
---|
275 | <div class="content inline-demo" markdown="1" data-demo="demo2"> |
---|
276 | <pre class="code" id="demo2"> |
---|
277 | var schema = { |
---|
278 | "type": "array", |
---|
279 | "items": {"$ref": "#"} |
---|
280 | }; |
---|
281 | var data1 = [[], [[]]]; |
---|
282 | var data2 = [[], [true, []]]; |
---|
283 | |
---|
284 | alert("data 1: " + tv4.validate(data1, schema)); // true |
---|
285 | alert("data 2: " + tv4.validate(data2, schema)); // false |
---|
286 | </pre> |
---|
287 | </div> |
---|
288 | |
---|
289 | ### Missing schema |
---|
290 | <div class="content inline-demo" markdown="1" data-demo="demo3"> |
---|
291 | <pre class="code" id="demo3"> |
---|
292 | var schema = { |
---|
293 | "type": "array", |
---|
294 | "items": {"$ref": "http://example.com/schema" } |
---|
295 | }; |
---|
296 | var data = [1, 2, 3]; |
---|
297 | |
---|
298 | alert("Valid: " + tv4.validate(data, schema)); // true |
---|
299 | alert("Missing schemas: " + JSON.stringify(tv4.missing)); |
---|
300 | </pre> |
---|
301 | </div> |
---|
302 | |
---|
303 | ### Referencing remote schema |
---|
304 | <div class="content inline-demo" markdown="1" data-demo="demo4"> |
---|
305 | <pre class="code" id="demo4"> |
---|
306 | tv4.addSchema("http://example.com/schema", { |
---|
307 | "definitions": { |
---|
308 | "arrayItem": {"type": "boolean"} |
---|
309 | } |
---|
310 | }); |
---|
311 | var schema = { |
---|
312 | "type": "array", |
---|
313 | "items": {"$ref": "http://example.com/schema#/definitions/arrayItem" } |
---|
314 | }; |
---|
315 | var data1 = [true, false, true]; |
---|
316 | var data2 = [1, 2, 3]; |
---|
317 | |
---|
318 | alert("data 1: " + tv4.validate(data1, schema)); // true |
---|
319 | alert("data 2: " + tv4.validate(data2, schema)); // false |
---|
320 | </pre> |
---|
321 | </div> |
---|
322 | |
---|
323 | ## Supported platforms |
---|
324 | |
---|
325 | * Node.js |
---|
326 | * All modern browsers |
---|
327 | * IE >= 7 |
---|
328 | |
---|
329 | ## Installation |
---|
330 | |
---|
331 | You can manually download [`tv4.js`](https://raw.github.com/geraintluff/tv4/master/tv4.js) or the minified [`tv4.min.js`](https://raw.github.com/geraintluff/tv4/master/tv4.min.js) and include it in your html to create the global `tv4` variable. |
---|
332 | |
---|
333 | Alternately use it as a CommonJS module: |
---|
334 | |
---|
335 | ````js |
---|
336 | var tv4 = require('tv4'); |
---|
337 | ```` |
---|
338 | |
---|
339 | #### npm |
---|
340 | |
---|
341 | ```` |
---|
342 | $ npm install tv4 |
---|
343 | ```` |
---|
344 | |
---|
345 | #### bower |
---|
346 | |
---|
347 | ```` |
---|
348 | $ bower install tv4 |
---|
349 | ```` |
---|
350 | |
---|
351 | #### component.io |
---|
352 | |
---|
353 | ```` |
---|
354 | $ component install geraintluff/tv4 |
---|
355 | ```` |
---|
356 | |
---|
357 | ## Build and test |
---|
358 | |
---|
359 | You can rebuild and run the node and browser tests using node.js and [grunt](http://http://gruntjs.com/): |
---|
360 | |
---|
361 | Make sure you have the global grunt cli command: |
---|
362 | ```` |
---|
363 | $ npm install grunt-cli -g |
---|
364 | ```` |
---|
365 | |
---|
366 | Clone the git repos, open a shell in the root folder and install the development dependencies: |
---|
367 | |
---|
368 | ```` |
---|
369 | $ npm install |
---|
370 | ```` |
---|
371 | |
---|
372 | Rebuild and run the tests: |
---|
373 | ```` |
---|
374 | $ grunt |
---|
375 | ```` |
---|
376 | |
---|
377 | It will run a build and display one Spec-style report for the node.js and two Dot-style reports for both the plain and minified browser tests (via phantomJS). You can also use your own browser to manually run the suites by opening [`test/index.html`](http://geraintluff.github.io/tv4/test/index.html) and [`test/index-min.html`](http://geraintluff.github.io/tv4/test/index-min.html). |
---|
378 | |
---|
379 | ## Contributing |
---|
380 | |
---|
381 | Pull-requests for fixes and expansions are welcome. Edit the partial files in `/source` and add your tests in a suitable suite or folder under `/test/tests` and run `grunt` to rebuild and run the test suite. Try to maintain an idiomatic coding style and add tests for any new features. It is recommend to discuss big changes in an Issue. |
---|
382 | |
---|
383 | ## Packages using tv4 |
---|
384 | |
---|
385 | * [chai-json-schema](http://chaijs.com/plugins/chai-json-schema) is a [Chai Assertion Library](http://chaijs.com) plugin to assert values against json-schema. |
---|
386 | * [grunt-tv4](http://www.github.com/Bartvds/grunt-tv4) is a plugin for [Grunt](http://http://gruntjs.com/) that uses tv4 to bulk validate json files. |
---|
387 | |
---|
388 | ## License |
---|
389 | |
---|
390 | The code is available as "public domain", meaning that it is completely free to use, without any restrictions at all. Read the full license [here](http://geraintluff.github.com/tv4/LICENSE.txt). |
---|
391 | |
---|
392 | It's also available under an [MIT license](http://jsonary.com/LICENSE.txt). |
---|