Security update for permissions_by_term
[yaffs-website] / node_modules / ajv / README.md
1 # Ajv: Another JSON Schema Validator
2
3 The fastest JSON Schema validator for node.js and browser. Supports [v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals).
4
5
6 [![Build Status](https://travis-ci.org/epoberezkin/ajv.svg?branch=master)](https://travis-ci.org/epoberezkin/ajv)
7 [![npm version](https://badge.fury.io/js/ajv.svg)](https://www.npmjs.com/package/ajv)
8 [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv)
9 [![Code Climate](https://codeclimate.com/github/epoberezkin/ajv/badges/gpa.svg)](https://codeclimate.com/github/epoberezkin/ajv)
10 [![Coverage Status](https://coveralls.io/repos/epoberezkin/ajv/badge.svg?branch=master&service=github)](https://coveralls.io/github/epoberezkin/ajv?branch=master)
11 [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
12
13
14 __Please note__: You can start using NEW beta version [5.0.3](https://github.com/epoberezkin/ajv/releases/tag/5.0.3-beta.0) (see [migration guide from 4.x.x](https://github.com/epoberezkin/ajv/releases/tag/5.0.1-beta.0)) with the support of JSON-Schema draft-06 (not officially published yet): `npm install ajv@^5.0.3-beta`.
15
16 Also see [docs](https://github.com/epoberezkin/ajv/tree/5.0.3-beta.0) for 5.0.3.
17
18
19 ## Contents
20
21 - [Performance](#performance)
22 - [Features](#features)
23 - [Getting started](#getting-started)
24 - [Frequently Asked Questions](https://github.com/epoberezkin/ajv/blob/master/FAQ.md)
25 - [Using in browser](#using-in-browser)
26 - [Command line interface](#command-line-interface)
27 - Validation
28   - [Keywords](#validation-keywords)
29   - [Formats](#formats)
30   - [$data reference](#data-reference)
31   - NEW: [$merge and $patch keywords](#merge-and-patch-keywords)
32   - [Defining custom keywords](#defining-custom-keywords)
33   - [Asynchronous schema compilation](#asynchronous-compilation)
34   - [Asynchronous validation](#asynchronous-validation)
35 - Modifying data during validation
36   - [Filtering data](#filtering-data)
37   - [Assigning defaults](#assigning-defaults)
38   - [Coercing data types](#coercing-data-types)
39 - API
40   - [Methods](#api)
41   - [Options](#options)
42   - [Validation errors](#validation-errors)
43 - [Related packages](#related-packages)
44 - [Packages using Ajv](#some-packages-using-ajv)
45 - [Tests, Contributing, History, License](#tests)
46
47
48 ## Performance
49
50 Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON schemas into super-fast validation functions that are efficient for v8 optimization.
51
52 Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks:
53
54 - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place
55 - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster
56 - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html)
57 - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html)
58
59
60 Performace of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark):
61
62 [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:%7Cajv%7Cis-my-json-valid%7Cjsen%7Cschemasaurus%7Cthemis%7Cz-schema%7Cjsck%7Cjsonschema%7Cskeemas%7Ctv4%7Cjayschema&chd=t:100,68,61,22.8,17.6,6.6,2.7,0.9,0.7,0.4,0.1)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance)
63
64
65 ## Features
66
67 - Ajv implements full [JSON Schema draft 4](http://json-schema.org/) standard:
68   - all validation keywords (see [JSON-Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md))
69   - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available)
70   - support of circular references between schemas
71   - correct string lengths for strings with unicode pairs (can be turned off)
72   - [formats](#formats) defined by JSON Schema draft 4 standard and custom formats (can be turned off)
73   - [validates schemas against meta-schema](#api-validateschema)
74 - supports [browsers](#using-in-browser) and nodejs 0.10-6.x
75 - [asynchronous loading](#asynchronous-compilation) of referenced schemas during compilation
76 - "All errors" validation mode with [option allErrors](#options)
77 - [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages
78 - i18n error messages support with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package
79 - [filtering data](#filtering-data) from additional properties
80 - [assigning defaults](#assigning-defaults) to missing properties and items
81 - [coercing data](#coercing-data-types) to the types specified in `type` keywords
82 - [custom keywords](#defining-custom-keywords)
83 - keywords `switch`, `constant`, `contains`, `patternGroups`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON-schema v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [option v5](#options)
84 - [v5 meta-schema](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#) for schemas using v5 keywords
85 - [v5 $data reference](#data-reference) to use values from the validated data as values for the schema keywords
86 - [asynchronous validation](#asynchronous-validation) of custom formats and keywords
87
88 Currently Ajv is the only validator that passes all the tests from [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (according to [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark), apart from the test that requires that `1.0` is not an integer that is impossible to satisfy in JavaScript).
89
90
91 ## Install
92
93 ```
94 npm install ajv
95 ```
96
97 To install a stable beta version [5.0.3](https://github.com/epoberezkin/ajv/releases/tag/5.0.3-beta.0) (see [migration guide from 4.x.x](https://github.com/epoberezkin/ajv/releases/tag/5.0.1-beta.0)):
98
99 ```
100 npm install ajv@^5.0.3-beta
101 ```
102
103
104 ## <a name="usage"></a>Getting started
105
106 Try it in the node REPL: https://tonicdev.com/npm/ajv
107
108
109 The fastest validation call:
110
111 ```javascript
112 var Ajv = require('ajv');
113 var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
114 var validate = ajv.compile(schema);
115 var valid = validate(data);
116 if (!valid) console.log(validate.errors);
117 ```
118
119 or with less code
120
121 ```javascript
122 // ...
123 var valid = ajv.validate(schema, data);
124 if (!valid) console.log(ajv.errors);
125 // ...
126 ```
127
128 or
129
130 ```javascript
131 // ...
132 ajv.addSchema(schema, 'mySchema');
133 var valid = ajv.validate('mySchema', data);
134 if (!valid) console.log(ajv.errorsText());
135 // ...
136 ```
137
138 See [API](#api) and [Options](#options) for more details.
139
140 Ajv compiles schemas to functions and caches them in all cases (using schema stringified with [json-stable-stringify](https://github.com/substack/json-stable-stringify) as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again.
141
142 The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call).
143
144 __Please note__: every time validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors)
145
146
147 ## Using in browser
148
149 You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle.
150
151 If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)).
152
153 Then you need to load Ajv in the browser:
154 ```html
155 <script src="ajv.min.js"></script>
156 ```
157
158 This bundle can be used with different module systems or creates global `Ajv` if no module system is found.
159
160 The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv).
161
162 Ajv is tested with these browsers:
163
164 [![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin)
165
166 __Please note__: some frameworks, e.g. Dojo, may redifine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/epoberezkin/ajv/issues/234)).
167
168
169 ## Command line interface
170
171 CLI is available as a separate npm package [ajv-cli](https://github.com/jessedc/ajv-cli). It supports:
172
173 - compiling JSON-schemas to test their validity
174 - BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/epoberezkin/ajv-pack))
175 - validating data file(s) against JSON-schema
176 - testing expected validity of data against JSON-schema
177 - referenced schemas
178 - custom meta-schemas
179 - files in JSON and JavaScript format
180 - all Ajv options
181 - reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format
182
183
184 ## Validation keywords
185
186 Ajv supports all validation keywords from draft 4 of JSON-schema standard:
187
188 - [type](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#type)
189 - [for numbers](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf
190 - [for strings](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format
191 - [for arrays](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems
192 - [for objects](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minproperties, required, properties, patternProperties, additionalProperties, dependencies
193 - [compound keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, not, oneOf, anyOf, allOf
194
195 With option `v5: true` Ajv also supports all validation keywords and [$data reference](#data-reference) from [v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON-schema standard:
196
197 - [switch](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#switch-v5-proposal) - conditional validation with a sequence of if/then clauses
198 - [contains](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#contains-v5-proposal) - check that array contains a valid item
199 - [constant](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#constant-v5-proposal) - check that data is equal to some value
200 - [patternGroups](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#patterngroups-v5-proposal) - a more powerful alternative to patternProperties
201 - [patternRequired](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#patternrequired-v5-proposal) - like `required` but with patterns that some property should match.
202 - [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-v5-proposal) - setting limits for date, time, etc.
203
204 See [JSON-Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md) for more details.
205
206
207 ## Formats
208
209 The following formats are supported for string validation with "format" keyword:
210
211 - _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6).
212 - _time_: time with optional time-zone.
213 - _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)).
214 - _uri_: full uri with optional protocol.
215 - _email_: email address.
216 - _hostname_: host name acording to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5).
217 - _ipv4_: IP address v4.
218 - _ipv6_: IP address v6.
219 - _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor.
220 - _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122).
221 - _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901).
222 - _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00).
223
224 There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `email`, and `hostname`. See [Options](#options) for details.
225
226 You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method.
227
228 The option `unknownFormats` allows to change the behaviour in case an unknown format is encountered - Ajv can either ignore them (default now) or fail schema compilation (will be the default in 5.0.0).
229
230 You can find patterns used for format validation and the sources that were used in [formats.js](https://github.com/epoberezkin/ajv/blob/master/lib/compile/formats.js).
231
232
233 ## $data reference
234
235 With `v5` option you can use values from the validated data as the values for the schema keywords. See [v5 proposal](https://github.com/json-schema/json-schema/wiki/$data-(v5-proposal)) for more information about how it works.
236
237 `$data` reference is supported in the keywords: constant, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems.
238
239 The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema).
240
241 Examples.
242
243 This schema requires that the value in property `smaller` is less or equal than the value in the property larger:
244
245 ```javascript
246 var schema = {
247   "properties": {
248     "smaller": {
249       "type": "number",
250       "maximum": { "$data": "1/larger" }
251     },
252     "larger": { "type": "number" }
253   }
254 };
255
256 var validData = {
257   smaller: 5,
258   larger: 7
259 };
260 ```
261
262 This schema requires that the properties have the same format as their field names:
263
264 ```javascript
265 var schema = {
266   "additionalProperties": {
267     "type": "string",
268     "format": { "$data": "0#" }
269   }
270 };
271
272 var validData = {
273   'date-time': '1963-06-19T08:30:06.283185Z',
274   email: 'joe.bloggs@example.com'
275 }
276 ```
277
278 `$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `constant` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails.
279
280
281 ## $merge and $patch keywords
282
283 With v5 option and the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON-schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902).
284
285 To add keywords `$merge` and `$patch` to Ajv instance use this code:
286
287 ```javascript
288 require('ajv-merge-patch')(ajv);
289 ```
290
291 Examples.
292
293 Using `$merge`:
294
295 ```json
296 {
297   "$merge": {
298     "source": {
299       "type": "object",
300       "properties": { "p": { "type": "string" } },
301       "additionalProperties": false
302     },
303     "with": {
304       "properties": { "q": { "type": "number" } }
305     }
306   }
307 }
308 ```
309
310 Using `$patch`:
311
312 ```json
313 {
314   "$patch": {
315     "source": {
316       "type": "object",
317       "properties": { "p": { "type": "string" } },
318       "additionalProperties": false
319     },
320     "with": [
321       { "op": "add", "path": "/properties/q", "value": { "type": "number" } }
322     ]
323   }
324 }
325 ```
326
327 The schemas above are equivalent to this schema:
328
329 ```json
330 {
331   "type": "object",
332   "properties": {
333     "p": { "type": "string" },
334     "q": { "type": "number" }
335   },
336   "additionalProperties": false
337 }
338 ```
339
340 The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema.
341
342 See the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) for more information.
343
344
345 ## Defining custom keywords
346
347 The advantages of using custom keywords are:
348
349 - allow creating validation scenarios that cannot be expressed using JSON-Schema
350 - simplify your schemas
351 - help bringing a bigger part of the validation logic to your schemas
352 - make your schemas more expressive, less verbose and closer to your application domain
353 - implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated
354
355 If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result).
356
357 The concerns you have to be aware of when extending JSON-schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas.
358
359 You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords.
360
361 Ajv allows defining keywords with:
362 - validation function
363 - compilation function
364 - macro function
365 - inline compilation function that should return code (as string) that will be inlined in the currently compiled schema.
366
367 Example. `range` and `exclusiveRange` keywords using compiled schema:
368
369 ```javascript
370 ajv.addKeyword('range', { type: 'number', compile: function (sch, parentSchema) {
371   var min = sch[0];
372   var max = sch[1];
373
374   return parentSchema.exclusiveRange === true
375           ? function (data) { return data > min && data < max; }
376           : function (data) { return data >= min && data <= max; }
377 } });
378
379 var schema = { "range": [2, 4], "exclusiveRange": true };
380 var validate = ajv.compile(schema);
381 console.log(validate(2.01)); // true
382 console.log(validate(3.99)); // true
383 console.log(validate(2)); // false
384 console.log(validate(4)); // false
385 ```
386
387 Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords.
388
389 See [Defining custom keywords](https://github.com/epoberezkin/ajv/blob/master/CUSTOM.md) for more details.
390
391
392 ## Asynchronous compilation
393
394 During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` method and `loadSchema` [option](#options).
395
396 Example:
397
398 ```javascript
399 var ajv = new Ajv({ loadSchema: loadSchema });
400
401 ajv.compileAsync(schema, function (err, validate) {
402         if (err) return;
403         var valid = validate(data);
404 });
405
406 function loadSchema(uri, callback) {
407         request.json(uri, function(err, res, body) {
408                 if (err || res.statusCode >= 400)
409                         callback(err || new Error('Loading error: ' + res.statusCode));
410                 else
411                         callback(null, body);
412         });
413 }
414 ```
415
416 __Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work.
417
418
419 ## Asynchronous validation
420
421 Example in node REPL: https://tonicdev.com/esp/ajv-asynchronous-validation
422
423 You can define custom formats and keywords that perform validation asyncronously by accessing database or some service. You should add `async: true` in the keyword or format defnition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)).
424
425 If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation.
426
427 __Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail.
428
429 Validation function for an asynchronous custom format/keyword should return a promise that resolves to `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to either [generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) (default) that can be optionally transpiled with [regenerator](https://github.com/facebook/regenerator) or to [es7 async function](http://tc39.github.io/ecmascript-asyncawait/) that can be transpiled with [nodent](https://github.com/MatAtBread/nodent) or with regenerator as well. You can also supply any other transpiler as a function. See [Options](#options).
430
431 The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both syncronous and asynchronous schemas.
432
433 If you are using generators, the compiled validation function can be either wrapped with [co](https://github.com/tj/co) (default) or returned as generator function, that can be used directly, e.g. in [koa](http://koajs.com/) 1.0. `co` is a small library, it is included in Ajv (both as npm dependency and in the browser bundle).
434
435 Generator functions are currently supported in Chrome, Firefox and node.js (0.11+); if you are using Ajv in other browsers or in older versions of node.js you should use one of available transpiling options. All provided async modes use global Promise class. If your platform does not have Promise you should use a polyfill that defines it.
436
437 Validation result will be a promise that resolves to `true` or rejects with an exception `Ajv.ValidationError` that has the array of validation errors in `errors` property.
438
439
440 Example:
441
442 ```javascript
443 /**
444  * without "async" and "transpile" options (or with option {async: true})
445  * Ajv will choose the first supported/installed option in this order:
446  * 1. native generator function wrapped with co
447  * 2. es7 async functions transpiled with nodent
448  * 3. es7 async functions transpiled with regenerator
449  */
450
451 var ajv = new Ajv;
452
453 ajv.addKeyword('idExists', {
454   async: true,
455   type: 'number',
456   validate: checkIdExists
457 });
458
459
460 function checkIdExists(schema, data) {
461   return knex(schema.table)
462   .select('id')
463   .where('id', data)
464   .then(function (rows) {
465     return !!rows.length; // true if record is found
466   });
467 }
468
469 var schema = {
470   "$async": true,
471   "properties": {
472     "userId": {
473       "type": "integer",
474       "idExists": { "table": "users" }
475     },
476     "postId": {
477       "type": "integer",
478       "idExists": { "table": "posts" }
479     }
480   }
481 };
482
483 var validate = ajv.compile(schema);
484
485 validate({ userId: 1, postId: 19 }))
486 .then(function (valid) {
487   // "valid" is always true here
488   console.log('Data is valid');
489 })
490 .catch(function (err) {
491   if (!(err instanceof Ajv.ValidationError)) throw err;
492   // data is invalid
493   console.log('Validation errors:', err.errors);
494 });
495
496 ```
497
498 ### Using transpilers with asyncronous validation functions.
499
500 To use a transpiler you should separately install it (or load its bundle in the browser).
501
502 Ajv npm package includes minified browser bundles of regenerator and nodent in dist folder.
503
504
505 #### Using nodent
506
507 ```javascript
508 var ajv = new Ajv({ /* async: 'es7', */ transpile: 'nodent' });
509 var validate = ajv.compile(schema); // transpiled es7 async function
510 validate(data).then(successFunc).catch(errorFunc);
511 ```
512
513 `npm install nodent` or use `nodent.min.js` from dist folder of npm package.
514
515
516 #### Using regenerator
517
518 ```javascript
519 var ajv = new Ajv({ /* async: 'es7', */ transpile: 'regenerator' });
520 var validate = ajv.compile(schema); // transpiled es7 async function
521 validate(data).then(successFunc).catch(errorFunc);
522 ```
523
524 `npm install regenerator` or use `regenerator.min.js` from dist folder of npm package.
525
526
527 #### Using other transpilers
528
529 ```javascript
530 var ajv = new Ajv({ async: 'es7', transpile: transpileFunc });
531 var validate = ajv.compile(schema); // transpiled es7 async function
532 validate(data).then(successFunc).catch(errorFunc);
533 ```
534
535 See [Options](#options).
536
537
538 #### Comparison of async modes
539
540 |mode|transpile<br>speed*|run-time<br>speed*|bundle<br>size|
541 |---|:-:|:-:|:-:|
542 |generators<br>(native)|-|1.0|-|
543 |es7.nodent|1.35|1.1|183Kb|
544 |es7.regenerator|1.0|2.7|322Kb|
545 |regenerator|1.0|3.2|322Kb|
546
547 \* Relative performance in node v.4, smaller is better.
548
549 [nodent](https://github.com/MatAtBread/nodent) has several advantages:
550
551 - much smaller browser bundle than regenerator
552 - almost the same performance of generated code as native generators in nodejs and the latest Chrome
553 - much better performace than native generators in other browsers
554 - works in IE 9 (regenerator does not)
555
556 [regenerator](https://github.com/facebook/regenerator) is a more widely adopted alternative.
557
558
559 ## Filtering data
560
561 With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation.
562
563 This option modifies original data.
564
565 Example:
566
567 ```javascript
568 var ajv = new Ajv({ removeAdditional: true });
569 var schema = {
570   "additionalProperties": false,
571   "properties": {
572     "foo": { "type": "number" },
573     "bar": {
574       "additionalProperties": { "type": "number" },
575       "properties": {
576         "baz": { "type": "string" }
577       }
578     }
579   }
580 }
581
582 var data = {
583   "foo": 0,
584   "additional1": 1, // will be removed; `additionalProperties` == false
585   "bar": {
586     "baz": "abc",
587     "additional2": 2 // will NOT be removed; `additionalProperties` != false
588   },
589 }
590
591 var validate = ajv.compile(schema);
592
593 console.log(validate(data)); // true
594 console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 }
595 ```
596
597 If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed.
598
599 If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed).
600
601 __Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example:
602
603 ```JSON
604 {
605   "type": "object",
606   "oneOf": [
607     {
608       "properties": {
609         "foo": { "type": "string" }
610       },
611       "required": [ "foo" ],
612       "additionalProperties": false
613     },
614     {
615       "properties": {
616         "bar": { "type": "integer" }
617       },
618       "required": [ "bar" ],
619       "additionalProperties": false
620     }
621   ]
622 }
623 ```
624
625 The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties.
626
627 With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema).
628
629 While this behaviour is unexpected (issues [#129](https://github.com/epoberezkin/ajv/issues/129), [#134](https://github.com/epoberezkin/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way:
630
631 ```JSON
632 {
633   "type": "object",
634   "properties": {
635     "foo": { "type": "string" },
636     "bar": { "type": "integer" }
637   },
638   "additionalProperties": false,
639   "oneOf": [
640     { "required": [ "foo" ] },
641     { "required": [ "bar" ] }
642   ]
643 }
644 ```
645
646 The schema above is also more efficient - it will compile into a faster function.
647
648
649 ## Assigning defaults
650
651 With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items.
652
653 This option modifies original data.
654
655 __Please note__: by default the default value is inserted in the generated validation code as a literal (starting from v4.0), so the value inserted in the data will be the deep clone of the default in the schema.
656
657 If you need to insert the default value in the data by reference pass the option `useDefaults: "shared"`.
658
659 Inserting defaults by reference can be faster (in case you have an object in `default`) and it allows to have dynamic values in defaults, e.g. timestamp, without recompiling the schema. The side effect is that modifying the default value in any validated data instance will change the default in the schema and in other validated data instances. See example 3 below.
660
661
662 Example 1 (`default` in `properties`):
663
664 ```javascript
665 var ajv = new Ajv({ useDefaults: true });
666 var schema = {
667   "type": "object",
668   "properties": {
669     "foo": { "type": "number" },
670     "bar": { "type": "string", "default": "baz" }
671   },
672   "required": [ "foo", "bar" ]
673 };
674
675 var data = { "foo": 1 };
676
677 var validate = ajv.compile(schema);
678
679 console.log(validate(data)); // true
680 console.log(data); // { "foo": 1, "bar": "baz" }
681 ```
682
683 Example 2 (`default` in `items`):
684
685 ```javascript
686 var schema = {
687   "type": "array",
688   "items": [
689     { "type": "number" },
690     { "type": "string", "default": "foo" }
691   ]
692 }
693
694 var data = [ 1 ];
695
696 var validate = ajv.compile(schema);
697
698 console.log(validate(data)); // true
699 console.log(data); // [ 1, "foo" ]
700 ```
701
702 Example 3 (inserting "defaults" by reference):
703
704 ```javascript
705 var ajv = new Ajv({ useDefaults: 'shared' });
706
707 var schema = {
708   properties: {
709     foo: {
710       default: { bar: 1 }
711     }
712   }
713 }
714
715 var validate = ajv.compile(schema);
716
717 var data = {};
718 console.log(validate(data)); // true
719 console.log(data); // { foo: { bar: 1 } }
720
721 data.foo.bar = 2;
722
723 var data2 = {};
724 console.log(validate(data2)); // true
725 console.log(data2); // { foo: { bar: 2 } }
726 ```
727
728 `default` keywords in other cases are ignored:
729
730 - not in `properties` or `items` subschemas
731 - in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/epoberezkin/ajv/issues/42))
732 - in `if` subschema of v5 `switch` keyword
733 - in schemas generated by custom macro keywords
734
735
736 ## Coercing data types
737
738 When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards.
739
740 This option modifies original data.
741
742 __Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value.
743
744
745 Example 1:
746
747 ```javascript
748 var ajv = new Ajv({ coerceTypes: true });
749 var schema = {
750   "type": "object",
751   "properties": {
752     "foo": { "type": "number" },
753     "bar": { "type": "boolean" }
754   },
755   "required": [ "foo", "bar" ]
756 };
757
758 var data = { "foo": "1", "bar": "false" };
759
760 var validate = ajv.compile(schema);
761
762 console.log(validate(data)); // true
763 console.log(data); // { "foo": 1, "bar": false }
764 ```
765
766 Example 2 (array coercions):
767
768 ```javascript
769 var ajv = new Ajv({ coerceTypes: 'array' });
770 var schema = {
771   "properties": {
772     "foo": { "type": "array", "items": { "type": "number" } },
773     "bar": { "type": "boolean" }
774   }
775 };
776
777 var data = { "foo": "1", "bar": ["false"] };
778
779 var validate = ajv.compile(schema);
780
781 console.log(validate(data)); // true
782 console.log(data); // { "foo": [1], "bar": false }
783 ```
784
785 The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords).
786
787 See [Coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md) for details.
788
789
790 ## API
791
792 ##### new Ajv(Object options) -&gt; Object
793
794 Create Ajv instance.
795
796 All the instance methods below are bound to the instance, so they can be used without the instance.
797
798
799 ##### .compile(Object schema) -&gt; Function&lt;Object data&gt;
800
801 Generate validating function and cache the compiled schema for future use.
802
803 Validating function returns boolean and has properties `errors` with the errors from the last validation (`null` if there were no errors) and `schema` with the reference to the original schema.
804
805 Unless the option `validateSchema` is false, the schema will be validated against meta-schema and if schema is invalid the error will be thrown. See [options](#options).
806
807
808 ##### .compileAsync(Object schema, Function callback)
809
810 Asyncronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. Callback will always be called with 2 parameters: error (or null) and validating function. Error will be not null in the following cases:
811
812 - missing schema can't be loaded (`loadSchema` calls callback with error).
813 - the schema containing missing reference is loaded, but the reference cannot be resolved.
814 - schema (or some referenced schema) is invalid.
815
816 The function compiles schema and loads the first missing schema multiple times, until all missing schemas are loaded.
817
818 See example in [Asynchronous compilation](#asynchronous-compilation).
819
820
821 ##### .validate(Object schema|String key|String ref, data) -&gt; Boolean
822
823 Validate data using passed schema (it will be compiled and cached).
824
825 Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference.
826
827 Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors).
828
829 __Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later.
830
831 If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation).
832
833
834 ##### .addSchema(Array&lt;Object&gt;|Object schema [, String key])
835
836 Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole.
837
838 Array of schemas can be passed (schemas should have ids), the second parameter will be ignored.
839
840 Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key.
841
842
843 Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data.
844
845 Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time.
846
847 By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option.
848
849
850 ##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key])
851
852 Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option).
853
854 There is no need to explicitly add draft 4 meta schema (http://json-schema.org/draft-04/schema and http://json-schema.org/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`.
855
856 With option `v5: true` [meta-schema that includes v5 keywords](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json) also added.
857
858
859 ##### <a name="api-validateschema"></a>.validateSchema(Object schema) -&gt; Boolean
860
861 Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON-Schema standard.
862
863 By default this method is called automatically when the schema is added, so you rarely need to use it directly.
864
865 If schema doesn't have `$schema` property it is validated against draft 4 meta-schema (option `meta` should not be false) or against [v5 meta-schema](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#) if option `v5` is true.
866
867 If schema has `$schema` property then the schema with this id (that should be previously added) is used to validate passed schema.
868
869 Errors will be available at `ajv.errors`.
870
871
872 ##### .getSchema(String key) -&gt; Function&lt;Object data&gt;
873
874 Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). Returned validating function has `schema` property with the reference to the original schema.
875
876
877 ##### .removeSchema([Object schema|String key|String ref|RegExp pattern])
878
879 Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references.
880
881 Schema can be removed using:
882 - key passed to `addSchema`
883 - it's full reference (id)
884 - RegExp that should match schema id or key (meta-schemas won't be removed)
885 - actual schema object that will be stable-stringified to remove schema from cache
886
887 If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared.
888
889
890 ##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format)
891
892 Add custom format to validate strings. It can also be used to replace pre-defined formats for Ajv instance.
893
894 Strings are converted to RegExp.
895
896 Function should return validation result as `true` or `false`.
897
898 If object is passed it should have properties `validate`, `compare` and `async`:
899
900 - _validate_: a string, RegExp or a function as described above.
901 - _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (from [v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) - `v5` option should be used). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal.
902 - _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`.
903
904 Custom formats can be also added via `formats` option.
905
906
907 ##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition)
908
909 Add custom validation keyword to Ajv instance.
910
911 Keyword should be different from all standard JSON schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance.
912
913 Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`.
914 It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions.
915
916 Example Keywords:
917 - `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions.
918 - `"example"`: valid, but not recommended as it could collide with future versions of JSON schema etc.
919 - `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword
920
921 Keyword definition is an object with the following properties:
922
923 - _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types.
924 - _validate_: validating function
925 - _compile_: compiling function
926 - _macro_: macro function
927 - _inline_: compiling function that returns code (as string)
928 - _schema_: an optional `false` value used with "validate" keyword to not pass schema
929 - _metaSchema_: an optional meta-schema for keyword schema
930 - _modifying_: `true` MUST be passed if keyword modifies data
931 - _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords.
932 - _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function).
933 - _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords.
934 - _errors_: an optional boolean indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation.
935
936 _compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference.
937
938 __Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed.
939
940 See [Defining custom keywords](#defining-custom-keywords) for more details.
941
942
943 ##### .getKeyword(String keyword) -&gt; Object|Boolean
944
945 Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown.
946
947
948 ##### .removeKeyword(String keyword)
949
950 Removes custom or pre-defined keyword so you can redefine them.
951
952 While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results.
953
954 __Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again.
955
956
957 ##### .errorsText([Array&lt;Object&gt; errors [, Object options]]) -&gt; String
958
959 Returns the text with all errors in a String.
960
961 Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default).
962
963
964 ## Options
965
966 Defaults:
967
968 ```javascript
969 {
970   // validation and reporting options:
971   v5:               false,
972   allErrors:        false,
973   verbose:          false,
974   jsonPointers:     false,
975   uniqueItems:      true,
976   unicode:          true,
977   format:           'fast',
978   formats:          {},
979   unknownFormats:   'ignore',
980   schemas:          {},
981   // referenced schema options:
982   missingRefs:      true,
983   extendRefs:       true,
984   loadSchema:       undefined, // function(uri, cb) { /* ... */ cb(err, schema); },
985   // options to modify validated data:
986   removeAdditional: false,
987   useDefaults:      false,
988   coerceTypes:      false,
989   // asynchronous validation options:
990   async:            undefined,
991   transpile:        undefined,
992   // advanced options:
993   meta:             true,
994   validateSchema:   true,
995   addUsedSchema:    true,
996   inlineRefs:       true,
997   passContext:      false,
998   loopRequired:     Infinity,
999   ownProperties:    false,
1000   multipleOfPrecision: false,
1001   errorDataPath:    'object',
1002   sourceCode:       true,
1003   messages:         true,
1004   beautify:         false,
1005   cache:            new Cache
1006 }
1007 ```
1008
1009 ##### Validation and reporting options
1010
1011 - _v5_: add keywords `switch`, `constant`, `contains`, `patternGroups`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON-schema v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals). With this option added schemas without `$schema` property are validated against [v5 meta-schema](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#). `false` by default.
1012 - _allErrors_: check all rules collecting all errors. Default is to return after the first error.
1013 - _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default).
1014 - _jsonPointers_: set `dataPath` propery of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation.
1015 - _uniqueItems_: validate `uniqueItems` keyword (true by default).
1016 - _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters.
1017 - _format_: formats validation mode ('fast' by default). Pass 'full' for more correct and slow validation or `false` not to validate formats at all. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode.
1018 - _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method.
1019 - _unknownFormats_: handling of unknown formats. Option values:
1020   - `true` (will be default in 5.0.0) - if the unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [v5 $data reference](#data-reference) and it is unknown the validation will fail.
1021   - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if some other unknown format is used. If `format` keyword value is [v5 $data reference](#data-reference) and it is not in this array the validation will fail.
1022   - `"ignore"` (default now) - to log warning during schema compilation and always pass validation. This option is not recommended, as it allows to mistype format name. This behaviour is required by JSON-schema specification.
1023 - _schemas_: an array or object of schemas that will be added to the instance. If the order is important, pass array. In this case schemas must have IDs in them. Otherwise the object can be passed - `addSchema(value, key)` will be called for each schema in this object.
1024
1025
1026 ##### Referenced schema options
1027
1028 - _missingRefs_: handling of missing referenced schemas. Option values:
1029   - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted).
1030   - `"ignore"` - to log error during compilation and always pass validation.
1031   - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked.
1032 - _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values:
1033   - `true` (default) - validate all keywords in the schemas with `$ref`.
1034   - `"ignore"` - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation.
1035   - `"fail"` - if other validation keywords are used together with `$ref` the exception will be throw when the schema is compiled.
1036 - _loadSchema_: asynchronous function that will be used to load remote schemas when the method `compileAsync` is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept 2 parameters: remote schema uri and node-style callback. See example in [Asynchronous compilation](#asynchronous-compilation).
1037
1038
1039 ##### Options to modify validated data
1040
1041 - _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values:
1042   - `false` (default) - not to remove additional properties
1043   - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them).
1044   - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed.
1045   - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema).
1046 - _useDefaults_: replace missing properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values:
1047   - `false` (default) - do not use defaults
1048   - `true` - insert defaults by value (safer and slower, object literal is used).
1049   - `"shared"` - insert defaults by reference (faster). If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well.
1050 - _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md). Option values:
1051   - `false` (default) - no type coercion.
1052   - `true` - coerce scalar data types.
1053   - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema).
1054
1055
1056 ##### Asynchronous validation options
1057
1058 - _async_: determines how Ajv compiles asynchronous schemas (see [Asynchronous validation](#asynchronous-validation)) to functions. Option values:
1059   - `"*"` / `"co*"` - compile to generator function ("co*" - wrapped with `co.wrap`). If generators are not supported and you don't provide `transpile` option, the exception will be thrown when Ajv instance is created.
1060   - `"es7"` - compile to es7 async function. Unless your platform supports them you need to provide `transpile` option. Currently only MS Edge 13 with flag supports es7 async functions according to [compatibility table](http://kangax.github.io/compat-table/es7/)).
1061   - `true` - if transpile option is not passed Ajv will choose the first supported/installed async/transpile modes in this order: "co*" (native generator with co.wrap), "es7"/"nodent", "co*"/"regenerator" during the creation of the Ajv instance. If none of the options is available the exception will be thrown.
1062   - `undefined`- Ajv will choose the first available async mode in the same way as with `true` option but when the first asynchronous schema is compiled.
1063 - _transpile_: determines whether Ajv transpiles compiled asynchronous validation function. Option values:
1064   - `"nodent"` - transpile with [nodent](https://github.com/MatAtBread/nodent). If nodent is not installed, the exception will be thrown. nodent can only transpile es7 async functions; it will enforce this mode.
1065   - `"regenerator"` - transpile with [regenerator](https://github.com/facebook/regenerator). If regenerator is not installed, the exception will be thrown.
1066   - a function - this function should accept the code of validation function as a string and return transpiled code. This option allows you to use any other transpiler you prefer.
1067
1068
1069 ##### Advanced options
1070
1071 - _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). With option `v5: true` [v5 meta-schema](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#) will be added as well. If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword.
1072 - _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can either be http://json-schema.org/schema or http://json-schema.org/draft-04/schema or absent (draft-4 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values:
1073   - `true` (default) -  if the validation fails, throw the exception.
1074   - `"log"` - if the validation fails, log error.
1075   - `false` - skip schema validation.
1076 - _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `id` property that doesn't start with "#". If `id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `id` uniqueness check when these methods are used. This option does not affect `addSchema` method.
1077 - _inlineRefs_: Affects compilation of referenced schemas. Option values:
1078   - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions.
1079   - `false` - to not inline referenced schemas (they will be compiled as separate functions).
1080   - integer number - to limit the maximum number of keywords of the schema that will be inlined.
1081 - _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance.
1082 - _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance.
1083 - _ownProperties_: by default ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst.
1084 - _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/epoberezkin/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations).
1085 - _errorDataPath_: set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`.
1086 - _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call).
1087 - _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n)).
1088 - _beautify_: format the generated function with [js-beautify](https://github.com/beautify-web/js-beautify) (the validating function is generated without line-breaks). `npm install js-beautify` to use this option. `true` or js-beautify options can be passed.
1089 - _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`.
1090
1091
1092 ## Validation errors
1093
1094 In case of validation failure Ajv assigns the array of errors to `.errors` property of validation function (or to `.errors` property of Ajv instance in case `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation) the returned promise is rejected with the exception of the class `Ajv.ValidationError` that has `.errors` poperty.
1095
1096
1097 ### Error objects
1098
1099 Each error is an object with the following properties:
1100
1101 - _keyword_: validation keyword.
1102 - _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`).
1103 - _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation.
1104 - _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package). See below for parameters set by all keywords.
1105 - _message_: the standard error message (can be excluded with option `messages` set to false).
1106 - _schema_: the schema of the keyword (added with `verbose` option).
1107 - _parentSchema_: the schema containing the keyword (added with `verbose` option)
1108 - _data_: the data validated by the keyword (added with `verbose` option).
1109
1110
1111 ### Error parameters
1112
1113 Properties of `params` object in errors depend on the keyword that failed validation.
1114
1115 - `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword).
1116 - `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false).
1117 - `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords).
1118 - `patternGroups` (with v5 option) - properties:
1119   - `pattern`
1120   - `reason` ("minimum"/"maximum"),
1121   - `limit` (max/min allowed number of properties matching number)
1122 - `dependencies` - properties:
1123   - `property` (dependent property),
1124   - `missingProperty` (required missing dependency - only the first one is reported currently)
1125   - `deps` (required dependencies, comma separated list as a string),
1126   - `depsCount` (the number of required dependedncies).
1127 - `format` - property `format` (the schema of the keyword).
1128 - `maximum`, `minimum` - properties:
1129   - `limit` (number, the schema of the keyword),
1130   - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`),
1131   - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=")
1132 - `multipleOf` - property `multipleOf` (the schema of the keyword)
1133 - `pattern` - property `pattern` (the schema of the keyword)
1134 - `required` - property `missingProperty` (required property that is missing).
1135 - `patternRequired` (with v5 option) - property `missingPattern` (required pattern that did not match any property).
1136 - `type` - property `type` (required type(s), a string, can be a comma-separated list)
1137 - `uniqueItems` - properties `i` and `j` (indices of duplicate items).
1138 - `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword).
1139 - `$ref` - property `ref` with the referenced schema URI.
1140 - custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name).
1141
1142
1143 ## Related packages
1144
1145 - [ajv-cli](https://github.com/epoberezkin/ajv-cli) - command line interface for Ajv
1146 - [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) - internationalised error messages
1147 - [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - keywords $merge and $patch from v5 proposals.
1148 - [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - several custom keywords that can be used with Ajv (typeof, instanceof, range, propertyNames)
1149
1150
1151 ## Some packages using Ajv
1152
1153 - [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services
1154 - [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition
1155 - [jsoneditor](https://github.com/josdejong/jsoneditor) - A web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org
1156 - [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - A web tool to validate JSON/YAML document against a single JSON-schema http://jsonschemalint.com
1157 - [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for node.js
1158 - [table](https://github.com/gajus/table) - formats data into a string table
1159 - [ripple-lib](https://github.com/ripple/ripple-lib) - A JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser
1160 - [restbase](https://github.com/wikimedia/restbase) - Distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content
1161 - [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation
1162 - [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation
1163 - [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - A schema definition module for RabbitMQ graphs and messages
1164 - [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema
1165 - [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON-schema with expect in mocha tests
1166 - [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON-Schema
1167 - [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter
1168 - [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages
1169
1170
1171 ## Tests
1172
1173 ```
1174 npm install
1175 git submodule update --init
1176 npm test
1177 ```
1178
1179 ## Contributing
1180
1181 All validation functions are generated using doT templates in [dot](https://github.com/epoberezkin/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency.
1182
1183 `npm run build` - compiles templates to [dotjs](https://github.com/epoberezkin/ajv/tree/master/lib/dotjs) folder.
1184
1185 `npm run watch` - automatically compiles templates when files in dot folder change
1186
1187 Please see [Contributing guidelines](https://github.com/epoberezkin/ajv/blob/master/CONTRIBUTING.md)
1188
1189
1190 ## Changes history
1191
1192 See https://github.com/epoberezkin/ajv/releases
1193
1194 __Please note__: [Changes in version 5.0.1-beta](https://github.com/epoberezkin/ajv/releases/tag/5.0.1-beta.0).
1195
1196 [Changes in version 4.6.0](https://github.com/epoberezkin/ajv/releases/tag/4.6.0).
1197
1198 [Changes in version 4.0.0](https://github.com/epoberezkin/ajv/releases/tag/4.0.0).
1199
1200 [Changes in version 3.0.0](https://github.com/epoberezkin/ajv/releases/tag/3.0.0).
1201
1202 [Changes in version 2.0.0](https://github.com/epoberezkin/ajv/releases/tag/2.0.0).
1203
1204
1205 ## License
1206
1207 [MIT](https://github.com/epoberezkin/ajv/blob/master/LICENSE)