source: Dev/trunk/src/node_modules/tv4/README.md @ 486

Last change on this file since 486 was 484, checked in by hendrikvanantwerpen, 11 years ago

Commit node_modules, to make checkouts and builds more deterministic.

File size: 10.6 KB
Line 
1# Tiny Validator (for v4 JSON Schema)
2
3[![Build Status](https://secure.travis-ci.org/geraintluff/tv4.png?branch=master)](http://travis-ci.org/geraintluff/tv4) [![Dependency Status](https://gemnasium.com/geraintluff/tv4.png)](https://gemnasium.com/geraintluff/tv4) [![NPM version](https://badge.fury.io/js/tv4.png)](http://badge.fury.io/js/tv4)
4
5Use [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
7There is support for `$ref` with JSON Pointer fragment paths (```other-schema.json#/properties/myKey```).
8
9## Usage 1: Simple validation
10
11```javascript
12var valid = tv4.validate(data, schema);
13```
14
15If validation returns ```false```, then an explanation of why validation failed can be found in ```tv4.error```.
16
17The 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
27The `"code"` property will refer to one of the values in `tv4.errorCodes` - in this case, `tv4.errorCodes.INVALID_TYPE`.
28
29To enable external schema to be referenced, you use:
30```javascript
31tv4.addSchema(url, schema);
32```
33
34If 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
38Storing the error and missing schemas does not work well in multi-threaded environments, so there is an alternative syntax:
39
40```javascript
41var result = tv4.validateResult(data, schema);
42```
43
44The result will look something like:
45```json
46{
47    "valid": false,
48    "error": {...},
49    "missing": [...]
50}
51```
52
53## Usage 3: Multiple errors
54
55Normally, `tv4` stops when it encounters the first validation error.  However, you can collect an array of validation errors using:
56
57```javascript
58var result = tv4.validateMultiple(data, schema);
59```
60
61The 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
75Support 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
77Usage:
78
79```javascript
80tv4.validate(data, schema, function (isValid, validationError) { ... });
81```
82
83`validationFailure` is simply taken from `tv4.error`.
84
85## Cyclical JavaScript objects
86
87While 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
89Consider this data, notice how both `a` and `b` refer to each other:
90
91```javascript
92var a = {};
93var b = { a: a };
94a.b = b;
95var aSchema = { properties: { b: { $ref: 'bSchema' }}};
96var bSchema = { properties: { a: { $ref: 'aSchema' }}};
97tv4.addSchema('aSchema', aSchema);
98tv4.addSchema('bSchema', bSchema);
99```
100
101If the final checkRecursive argument were missing, this would throw a "too much recursion" error.
102
103To enable supprot for this pass `true` as additional argument to any of the regular validation methods:
104
105```javascript
106tv4.validate(a, aSchema, true);
107tv4.validate(a, schema, asynchronousFunction, true);
108
109tv4.validateResult(data, aSchema, true);
110tv4.validateMultiple(data, aSchema, true);
111```
112
113## API
114
115There are additional api commands available for more complex use-cases:
116
117##### addSchema(uri, schema)
118Pre-register a schema for reference by other schema and synchronous validation.
119
120````js
121tv4.addSchema('http://example.com/schema', { ... });
122````
123
124* `uri` the uri to identify this schema.
125* `schema` the schema object.
126
127Schemas that have their `id` property set can be added directly.
128
129````js
130tv4.addSchema({ ... });
131````
132
133##### getSchema(uri)
134
135Return a schema from the cache.
136
137* `uri` the uri of the schema (may contain a `#` fragment)
138
139````js
140var schema = tv4.getSchema('http://example.com/schema');
141````
142
143##### getSchemaMap()
144
145Return a shallow copy of the schema cache, mapping schema document URIs to schema objects.
146
147````
148var map = tv4.getSchemaMap();
149
150var schema = map[uri];
151````
152
153##### getSchemaUris(filter)
154
155Return an Array with known schema document URIs.
156
157* `filter` optional RegExp to filter URIs
158
159````
160var arr = tv4.getSchemaUris();
161
162// optional filter using a RegExp
163var arr = tv4.getSchemaUris(/^https?://example.com/);
164````
165
166##### getMissingUris(filter)
167
168Return an Array with schema document URIs that are used as `$ref` in known schemas but which currently have no associated schema data.
169
170Use 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````
175var arr = tv4.getMissingUris();
176
177// optional filter using a RegExp
178var arr = tv4.getMissingUris(/^https?://example.com/);
179````
180
181##### dropSchemas()
182
183Drop all known schema document URIs from the cache.
184
185````
186tv4.dropSchemas();
187````
188
189##### freshApi()
190
191Return a new tv4 instance with no shared state.
192
193````
194var otherTV4 = tv4.freshApi();
195````
196
197##### reset()
198
199Manually 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````
202tv4.reset();
203````
204
205##### language(code)
206
207Select the language map used for reporting.
208
209* `code` is a language code, like `'en'` or `'en-gb'`
210
211````
212tv4.language('en-gb');
213````
214
215##### addLanguage(code, map)
216
217Add 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````
223tv4.addLanguage('fr', { ... });
224
225// select for use
226tv4.language('fr')
227````
228
229##### addFormat(format, validationFunction)
230
231Add 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````
239tv4.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
247Alternatively, multiple formats can be added at the same time using an object:
248````
249tv4.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">
260var schema = {
261        "items": {
262                "type": "boolean"
263        }
264};
265var data1 = [true, false];
266var data2 = [true, 123];
267
268alert("data 1: " + tv4.validate(data1, schema)); // true
269alert("data 2: " + tv4.validate(data2, schema)); // false
270alert("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">
277var schema = {
278        "type": "array",
279        "items": {"$ref": "#"}
280};
281var data1 = [[], [[]]];
282var data2 = [[], [true, []]];
283
284alert("data 1: " + tv4.validate(data1, schema)); // true
285alert("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">
292var schema = {
293        "type": "array",
294        "items": {"$ref": "http://example.com/schema" }
295};
296var data = [1, 2, 3];
297
298alert("Valid: " + tv4.validate(data, schema)); // true
299alert("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">
306tv4.addSchema("http://example.com/schema", {
307        "definitions": {
308                "arrayItem": {"type": "boolean"}
309        }
310});
311var schema = {
312        "type": "array",
313        "items": {"$ref": "http://example.com/schema#/definitions/arrayItem" }
314};
315var data1 = [true, false, true];
316var data2 = [1, 2, 3];
317
318alert("data 1: " + tv4.validate(data1, schema)); // true
319alert("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
331You 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
333Alternately use it as a CommonJS module:
334
335````js
336var 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
359You can rebuild and run the node and browser tests using node.js and [grunt](http://http://gruntjs.com/):
360
361Make sure you have the global grunt cli command:
362````
363$ npm install grunt-cli -g
364````
365
366Clone the git repos, open a shell in the root folder and install the development dependencies:
367
368````
369$ npm install
370````
371
372Rebuild and run the tests:
373````
374$ grunt
375````
376
377It 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
381Pull-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
390The 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
392It's also available under an [MIT license](http://jsonary.com/LICENSE.txt).
Note: See TracBrowser for help on using the repository browser.