UNPKG

71.3 kBMarkdownView Raw
1<img align="right" alt="Ajv logo" width="160" src="http://epoberezkin.github.io/ajv/images/ajv_logo.png">
2
3# Ajv: Another JSON Schema Validator
4
5The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07.
6
7
8[![Build Status](https://travis-ci.org/epoberezkin/ajv.svg?branch=master)](https://travis-ci.org/epoberezkin/ajv)
9[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv)
10[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv)
11[![Coverage Status](https://coveralls.io/repos/epoberezkin/ajv/badge.svg?branch=master&service=github)](https://coveralls.io/github/epoberezkin/ajv?branch=master)
12[![Greenkeeper badge](https://badges.greenkeeper.io/epoberezkin/ajv.svg)](https://greenkeeper.io/)
13[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
14
15
16## Using version 6
17
18[JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published.
19
20[Ajv version 6.0.0](https://github.com/epoberezkin/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes).
21
22__Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance:
23
24```javascript
25ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
26```
27
28To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId:
29
30```javascript
31var ajv = new Ajv({schemaId: 'id'});
32// If you want to use both draft-04 and draft-06/07 schemas:
33// var ajv = new Ajv({schemaId: 'auto'});
34ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
35```
36
37
38## Contents
39
40- [Performance](#performance)
41- [Features](#features)
42- [Getting started](#getting-started)
43- [Frequently Asked Questions](https://github.com/epoberezkin/ajv/blob/master/FAQ.md)
44- [Using in browser](#using-in-browser)
45- [Command line interface](#command-line-interface)
46- Validation
47 - [Keywords](#validation-keywords)
48 - [Annotation keywords](#annotation-keywords)
49 - [Formats](#formats)
50 - [Combining schemas with $ref](#ref)
51 - [$data reference](#data-reference)
52 - NEW: [$merge and $patch keywords](#merge-and-patch-keywords)
53 - [Defining custom keywords](#defining-custom-keywords)
54 - [Asynchronous schema compilation](#asynchronous-schema-compilation)
55 - [Asynchronous validation](#asynchronous-validation)
56- Modifying data during validation
57 - [Filtering data](#filtering-data)
58 - [Assigning defaults](#assigning-defaults)
59 - [Coercing data types](#coercing-data-types)
60- API
61 - [Methods](#api)
62 - [Options](#options)
63 - [Validation errors](#validation-errors)
64- [Plugins](#plugins)
65- [Related packages](#related-packages)
66- [Packages using Ajv](#some-packages-using-ajv)
67- [Tests, Contributing, History, License](#tests)
68
69
70## Performance
71
72Ajv 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.
73
74Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks:
75
76- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place
77- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster
78- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html)
79- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html)
80
81
82Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark):
83
84[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance)
85
86
87## Features
88
89- Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards:
90 - all validation keywords (see [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md))
91 - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available)
92 - support of circular references between schemas
93 - correct string lengths for strings with unicode pairs (can be turned off)
94 - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off)
95 - [validates schemas against meta-schema](#api-validateschema)
96- supports [browsers](#using-in-browser) and Node.js 0.10-8.x
97- [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation
98- "All errors" validation mode with [option allErrors](#options)
99- [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages
100- i18n error messages support with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package
101- [filtering data](#filtering-data) from additional properties
102- [assigning defaults](#assigning-defaults) to missing properties and items
103- [coercing data](#coercing-data-types) to the types specified in `type` keywords
104- [custom keywords](#defining-custom-keywords)
105- draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else`
106- draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail).
107- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package
108- [$data reference](#data-reference) to use values from the validated data as values for the schema keywords
109- [asynchronous validation](#asynchronous-validation) of custom formats and keywords
110
111Currently 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).
112
113
114## Install
115
116```
117npm install ajv
118```
119
120
121## <a name="usage"></a>Getting started
122
123Try it in the Node.js REPL: https://tonicdev.com/npm/ajv
124
125
126The fastest validation call:
127
128```javascript
129var Ajv = require('ajv');
130var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
131var validate = ajv.compile(schema);
132var valid = validate(data);
133if (!valid) console.log(validate.errors);
134```
135
136or with less code
137
138```javascript
139// ...
140var valid = ajv.validate(schema, data);
141if (!valid) console.log(ajv.errors);
142// ...
143```
144
145or
146
147```javascript
148// ...
149var valid = ajv.addSchema(schema, 'mySchema')
150 .validate('mySchema', data);
151if (!valid) console.log(ajv.errorsText());
152// ...
153```
154
155See [API](#api) and [Options](#options) for more details.
156
157Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function 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.
158
159The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call).
160
161__Please note__: every time a 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)
162
163
164## Using in browser
165
166You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle.
167
168If 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)).
169
170Then you need to load Ajv in the browser:
171```html
172<script src="ajv.min.js"></script>
173```
174
175This bundle can be used with different module systems; it creates global `Ajv` if no module system is found.
176
177The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv).
178
179Ajv is tested with these browsers:
180
181[![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin)
182
183__Please note__: some frameworks, e.g. Dojo, may redefine 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)).
184
185
186## Command line interface
187
188CLI is available as a separate npm package [ajv-cli](https://github.com/jessedc/ajv-cli). It supports:
189
190- compiling JSON Schemas to test their validity
191- BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/epoberezkin/ajv-pack))
192- migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate))
193- validating data file(s) against JSON Schema
194- testing expected validity of data against JSON Schema
195- referenced schemas
196- custom meta-schemas
197- files in JSON and JavaScript format
198- all Ajv options
199- reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format
200
201
202## Validation keywords
203
204Ajv supports all validation keywords from draft-07 of JSON Schema standard:
205
206- [type](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#type)
207- [for numbers](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf
208- [for strings](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format
209- [for arrays](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#contains)
210- [for objects](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#propertynames)
211- [for all types](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#const)
212- [compound keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#ifthenelse)
213
214With [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard:
215
216- [patternRequired](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match.
217- [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc.
218
219See [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md) for more details.
220
221
222## Annotation keywords
223
224JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation.
225
226- `title` and `description`: information about the data represented by that schema
227- `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options).
228- `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults).
229- `examples` (NEW in draft-07): an array of data instances. Ajv does not check the validity of these instances against the schema.
230- `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.).
231- `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64".
232- `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png".
233
234__Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance.
235
236
237## Formats
238
239The following formats are supported for string validation with "format" keyword:
240
241- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6).
242- _time_: time with optional time-zone.
243- _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)).
244- _uri_: full URI.
245- _uri-reference_: URI reference, including full and relative URIs.
246- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570)
247- _url_: [URL record](https://url.spec.whatwg.org/#concept-url).
248- _email_: email address.
249- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5).
250- _ipv4_: IP address v4.
251- _ipv6_: IP address v6.
252- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor.
253- _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122).
254- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901).
255- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00).
256
257__Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here.
258
259There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, `email`, and `hostname`. See [Options](#options) for details.
260
261You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method.
262
263The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can whitelist specific format(s) to be ignored. See [Options](#options) for details.
264
265You 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).
266
267
268## <a name="ref"></a>Combining schemas with $ref
269
270You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword.
271
272Example:
273
274```javascript
275var schema = {
276 "$id": "http://example.com/schemas/schema.json",
277 "type": "object",
278 "properties": {
279 "foo": { "$ref": "defs.json#/definitions/int" },
280 "bar": { "$ref": "defs.json#/definitions/str" }
281 }
282};
283
284var defsSchema = {
285 "$id": "http://example.com/schemas/defs.json",
286 "definitions": {
287 "int": { "type": "integer" },
288 "str": { "type": "string" }
289 }
290};
291```
292
293Now to compile your schema you can either pass all schemas to Ajv instance:
294
295```javascript
296var ajv = new Ajv({schemas: [schema, defsSchema]});
297var validate = ajv.getSchema('http://example.com/schemas/schema.json');
298```
299
300or use `addSchema` method:
301
302```javascript
303var ajv = new Ajv;
304var validate = ajv.addSchema(defsSchema)
305 .compile(schema);
306```
307
308See [Options](#options) and [addSchema](#api) method.
309
310__Please note__:
311- `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example).
312- References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.).
313- You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs.
314- The actual location of the schema file in the file system is not used.
315- You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id.
316- You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown.
317- You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation).
318
319
320## $data reference
321
322With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema/json-schema/wiki/$data-(v5-proposal)) for more information about how it works.
323
324`$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems.
325
326The 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).
327
328Examples.
329
330This schema requires that the value in property `smaller` is less or equal than the value in the property larger:
331
332```javascript
333var ajv = new Ajv({$data: true});
334
335var schema = {
336 "properties": {
337 "smaller": {
338 "type": "number",
339 "maximum": { "$data": "1/larger" }
340 },
341 "larger": { "type": "number" }
342 }
343};
344
345var validData = {
346 smaller: 5,
347 larger: 7
348};
349
350ajv.validate(schema, validData); // true
351```
352
353This schema requires that the properties have the same format as their field names:
354
355```javascript
356var schema = {
357 "additionalProperties": {
358 "type": "string",
359 "format": { "$data": "0#" }
360 }
361};
362
363var validData = {
364 'date-time': '1963-06-19T08:30:06.283185Z',
365 email: 'joe.bloggs@example.com'
366}
367```
368
369`$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 `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails.
370
371
372## $merge and $patch keywords
373
374With 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).
375
376To add keywords `$merge` and `$patch` to Ajv instance use this code:
377
378```javascript
379require('ajv-merge-patch')(ajv);
380```
381
382Examples.
383
384Using `$merge`:
385
386```json
387{
388 "$merge": {
389 "source": {
390 "type": "object",
391 "properties": { "p": { "type": "string" } },
392 "additionalProperties": false
393 },
394 "with": {
395 "properties": { "q": { "type": "number" } }
396 }
397 }
398}
399```
400
401Using `$patch`:
402
403```json
404{
405 "$patch": {
406 "source": {
407 "type": "object",
408 "properties": { "p": { "type": "string" } },
409 "additionalProperties": false
410 },
411 "with": [
412 { "op": "add", "path": "/properties/q", "value": { "type": "number" } }
413 ]
414 }
415}
416```
417
418The schemas above are equivalent to this schema:
419
420```json
421{
422 "type": "object",
423 "properties": {
424 "p": { "type": "string" },
425 "q": { "type": "number" }
426 },
427 "additionalProperties": false
428}
429```
430
431The 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.
432
433See the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) for more information.
434
435
436## Defining custom keywords
437
438The advantages of using custom keywords are:
439
440- allow creating validation scenarios that cannot be expressed using JSON Schema
441- simplify your schemas
442- help bringing a bigger part of the validation logic to your schemas
443- make your schemas more expressive, less verbose and closer to your application domain
444- 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
445
446If 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).
447
448The 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.
449
450You 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.
451
452Ajv allows defining keywords with:
453- validation function
454- compilation function
455- macro function
456- inline compilation function that should return code (as string) that will be inlined in the currently compiled schema.
457
458Example. `range` and `exclusiveRange` keywords using compiled schema:
459
460```javascript
461ajv.addKeyword('range', {
462 type: 'number',
463 compile: function (sch, parentSchema) {
464 var min = sch[0];
465 var max = sch[1];
466
467 return parentSchema.exclusiveRange === true
468 ? function (data) { return data > min && data < max; }
469 : function (data) { return data >= min && data <= max; }
470 }
471});
472
473var schema = { "range": [2, 4], "exclusiveRange": true };
474var validate = ajv.compile(schema);
475console.log(validate(2.01)); // true
476console.log(validate(3.99)); // true
477console.log(validate(2)); // false
478console.log(validate(4)); // false
479```
480
481Several 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.
482
483See [Defining custom keywords](https://github.com/epoberezkin/ajv/blob/master/CUSTOM.md) for more details.
484
485
486## Asynchronous schema compilation
487
488During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options).
489
490Example:
491
492```javascript
493var ajv = new Ajv({ loadSchema: loadSchema });
494
495ajv.compileAsync(schema).then(function (validate) {
496 var valid = validate(data);
497 // ...
498});
499
500function loadSchema(uri) {
501 return request.json(uri).then(function (res) {
502 if (res.statusCode >= 400)
503 throw new Error('Loading error: ' + res.statusCode);
504 return res.body;
505 });
506}
507```
508
509__Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work.
510
511
512## Asynchronous validation
513
514Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation
515
516You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)).
517
518If 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.
519
520__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.
521
522Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function).
523
524Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options).
525
526The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas.
527
528Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property.
529
530
531Example:
532
533```javascript
534var ajv = new Ajv;
535// require('ajv-async')(ajv);
536
537ajv.addKeyword('idExists', {
538 async: true,
539 type: 'number',
540 validate: checkIdExists
541});
542
543
544function checkIdExists(schema, data) {
545 return knex(schema.table)
546 .select('id')
547 .where('id', data)
548 .then(function (rows) {
549 return !!rows.length; // true if record is found
550 });
551}
552
553var schema = {
554 "$async": true,
555 "properties": {
556 "userId": {
557 "type": "integer",
558 "idExists": { "table": "users" }
559 },
560 "postId": {
561 "type": "integer",
562 "idExists": { "table": "posts" }
563 }
564 }
565};
566
567var validate = ajv.compile(schema);
568
569validate({ userId: 1, postId: 19 })
570.then(function (data) {
571 console.log('Data is valid', data); // { userId: 1, postId: 19 }
572})
573.catch(function (err) {
574 if (!(err instanceof Ajv.ValidationError)) throw err;
575 // data is invalid
576 console.log('Validation errors:', err.errors);
577});
578```
579
580### Using transpilers with asynchronous validation functions.
581
582[ajv-async](https://github.com/epoberezkin/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser).
583
584
585#### Using nodent
586
587```javascript
588var ajv = new Ajv;
589require('ajv-async')(ajv);
590// in the browser if you want to load ajv-async bundle separately you can:
591// window.ajvAsync(ajv);
592var validate = ajv.compile(schema); // transpiled es7 async function
593validate(data).then(successFunc).catch(errorFunc);
594```
595
596
597#### Using other transpilers
598
599```javascript
600var ajv = new Ajv({ processCode: transpileFunc });
601var validate = ajv.compile(schema); // transpiled es7 async function
602validate(data).then(successFunc).catch(errorFunc);
603```
604
605See [Options](#options).
606
607
608## Filtering data
609
610With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation.
611
612This option modifies original data.
613
614Example:
615
616```javascript
617var ajv = new Ajv({ removeAdditional: true });
618var schema = {
619 "additionalProperties": false,
620 "properties": {
621 "foo": { "type": "number" },
622 "bar": {
623 "additionalProperties": { "type": "number" },
624 "properties": {
625 "baz": { "type": "string" }
626 }
627 }
628 }
629}
630
631var data = {
632 "foo": 0,
633 "additional1": 1, // will be removed; `additionalProperties` == false
634 "bar": {
635 "baz": "abc",
636 "additional2": 2 // will NOT be removed; `additionalProperties` != false
637 },
638}
639
640var validate = ajv.compile(schema);
641
642console.log(validate(data)); // true
643console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 }
644```
645
646If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed.
647
648If 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).
649
650__Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example:
651
652```json
653{
654 "type": "object",
655 "oneOf": [
656 {
657 "properties": {
658 "foo": { "type": "string" }
659 },
660 "required": [ "foo" ],
661 "additionalProperties": false
662 },
663 {
664 "properties": {
665 "bar": { "type": "integer" }
666 },
667 "required": [ "bar" ],
668 "additionalProperties": false
669 }
670 ]
671}
672```
673
674The 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.
675
676With 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).
677
678While 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:
679
680```json
681{
682 "type": "object",
683 "properties": {
684 "foo": { "type": "string" },
685 "bar": { "type": "integer" }
686 },
687 "additionalProperties": false,
688 "oneOf": [
689 { "required": [ "foo" ] },
690 { "required": [ "bar" ] }
691 ]
692}
693```
694
695The schema above is also more efficient - it will compile into a faster function.
696
697
698## Assigning defaults
699
700With [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.
701
702This option modifies original data.
703
704__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.
705
706If you need to insert the default value in the data by reference pass the option `useDefaults: "shared"`.
707
708Inserting 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.
709
710
711Example 1 (`default` in `properties`):
712
713```javascript
714var ajv = new Ajv({ useDefaults: true });
715var schema = {
716 "type": "object",
717 "properties": {
718 "foo": { "type": "number" },
719 "bar": { "type": "string", "default": "baz" }
720 },
721 "required": [ "foo", "bar" ]
722};
723
724var data = { "foo": 1 };
725
726var validate = ajv.compile(schema);
727
728console.log(validate(data)); // true
729console.log(data); // { "foo": 1, "bar": "baz" }
730```
731
732Example 2 (`default` in `items`):
733
734```javascript
735var schema = {
736 "type": "array",
737 "items": [
738 { "type": "number" },
739 { "type": "string", "default": "foo" }
740 ]
741}
742
743var data = [ 1 ];
744
745var validate = ajv.compile(schema);
746
747console.log(validate(data)); // true
748console.log(data); // [ 1, "foo" ]
749```
750
751Example 3 (inserting "defaults" by reference):
752
753```javascript
754var ajv = new Ajv({ useDefaults: 'shared' });
755
756var schema = {
757 properties: {
758 foo: {
759 default: { bar: 1 }
760 }
761 }
762}
763
764var validate = ajv.compile(schema);
765
766var data = {};
767console.log(validate(data)); // true
768console.log(data); // { foo: { bar: 1 } }
769
770data.foo.bar = 2;
771
772var data2 = {};
773console.log(validate(data2)); // true
774console.log(data2); // { foo: { bar: 2 } }
775```
776
777`default` keywords in other cases are ignored:
778
779- not in `properties` or `items` subschemas
780- in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/epoberezkin/ajv/issues/42))
781- in `if` subschema of `switch` keyword
782- in schemas generated by custom macro keywords
783
784
785## Coercing data types
786
787When 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.
788
789This option modifies original data.
790
791__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.
792
793
794Example 1:
795
796```javascript
797var ajv = new Ajv({ coerceTypes: true });
798var schema = {
799 "type": "object",
800 "properties": {
801 "foo": { "type": "number" },
802 "bar": { "type": "boolean" }
803 },
804 "required": [ "foo", "bar" ]
805};
806
807var data = { "foo": "1", "bar": "false" };
808
809var validate = ajv.compile(schema);
810
811console.log(validate(data)); // true
812console.log(data); // { "foo": 1, "bar": false }
813```
814
815Example 2 (array coercions):
816
817```javascript
818var ajv = new Ajv({ coerceTypes: 'array' });
819var schema = {
820 "properties": {
821 "foo": { "type": "array", "items": { "type": "number" } },
822 "bar": { "type": "boolean" }
823 }
824};
825
826var data = { "foo": "1", "bar": ["false"] };
827
828var validate = ajv.compile(schema);
829
830console.log(validate(data)); // true
831console.log(data); // { "foo": [1], "bar": false }
832```
833
834The 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).
835
836See [Coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md) for details.
837
838
839## API
840
841##### new Ajv(Object options) -&gt; Object
842
843Create Ajv instance.
844
845
846##### .compile(Object schema) -&gt; Function&lt;Object data&gt;
847
848Generate validating function and cache the compiled schema for future use.
849
850Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema.
851
852The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options).
853
854
855##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -&gt; Promise
856
857Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when:
858
859- missing schema can't be loaded (`loadSchema` returns a Promise that rejects).
860- a schema containing a missing reference is loaded, but the reference cannot be resolved.
861- schema (or some loaded/referenced schema) is invalid.
862
863The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded.
864
865You can asynchronously compile meta-schema by passing `true` as the second parameter.
866
867See example in [Asynchronous compilation](#asynchronous-schema-compilation).
868
869
870##### .validate(Object schema|String key|String ref, data) -&gt; Boolean
871
872Validate data using passed schema (it will be compiled and cached).
873
874Instead 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.
875
876Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors).
877
878__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.
879
880If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation).
881
882
883##### .addSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv
884
885Add 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.
886
887Array of schemas can be passed (schemas should have ids), the second parameter will be ignored.
888
889Key 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.
890
891
892Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data.
893
894Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time.
895
896By 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.
897
898__Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`.
899This allows you to do nice things like the following.
900
901```javascript
902var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri);
903```
904
905##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv
906
907Adds 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).
908
909There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/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`.
910
911
912##### <a name="api-validateschema"></a>.validateSchema(Object schema) -&gt; Boolean
913
914Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard.
915
916By default this method is called automatically when the schema is added, so you rarely need to use it directly.
917
918If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false).
919
920If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema.
921
922Errors will be available at `ajv.errors`.
923
924
925##### .getSchema(String key) -&gt; Function&lt;Object data&gt;
926
927Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema.
928
929
930##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -&gt; Ajv
931
932Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references.
933
934Schema can be removed using:
935- key passed to `addSchema`
936- it's full reference (id)
937- RegExp that should match schema id or key (meta-schemas won't be removed)
938- actual schema object that will be stable-stringified to remove schema from cache
939
940If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared.
941
942
943##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format) -&gt; Ajv
944
945Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance.
946
947Strings are converted to RegExp.
948
949Function should return validation result as `true` or `false`.
950
951If object is passed it should have properties `validate`, `compare` and `async`:
952
953- _validate_: a string, RegExp or a function as described above.
954- _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` (defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package). 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.
955- _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`.
956- _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/epoberezkin/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass.
957
958Custom formats can be also added via `formats` option.
959
960
961##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition) -&gt; Ajv
962
963Add custom validation keyword to Ajv instance.
964
965Keyword 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.
966
967Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`.
968It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions.
969
970Example Keywords:
971- `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions.
972- `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc.
973- `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword
974
975Keyword definition is an object with the following properties:
976
977- _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.
978- _validate_: validating function
979- _compile_: compiling function
980- _macro_: macro function
981- _inline_: compiling function that returns code (as string)
982- _schema_: an optional `false` value used with "validate" keyword to not pass schema
983- _metaSchema_: an optional meta-schema for keyword schema
984- _modifying_: `true` MUST be passed if keyword modifies data
985- _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.
986- _$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).
987- _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.
988- _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.
989
990_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.
991
992__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.
993
994See [Defining custom keywords](#defining-custom-keywords) for more details.
995
996
997##### .getKeyword(String keyword) -&gt; Object|Boolean
998
999Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown.
1000
1001
1002##### .removeKeyword(String keyword) -&gt; Ajv
1003
1004Removes custom or pre-defined keyword so you can redefine them.
1005
1006While 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.
1007
1008__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.
1009
1010
1011##### .errorsText([Array&lt;Object&gt; errors [, Object options]]) -&gt; String
1012
1013Returns the text with all errors in a String.
1014
1015Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default).
1016
1017
1018## Options
1019
1020Defaults:
1021
1022```javascript
1023{
1024 // validation and reporting options:
1025 $data: false,
1026 allErrors: false,
1027 verbose: false,
1028 $comment: false, // NEW in Ajv version 6.0
1029 jsonPointers: false,
1030 uniqueItems: true,
1031 unicode: true,
1032 format: 'fast',
1033 formats: {},
1034 unknownFormats: true,
1035 schemas: {},
1036 logger: undefined,
1037 // referenced schema options:
1038 schemaId: '$id',
1039 missingRefs: true,
1040 extendRefs: 'ignore', // recommended 'fail'
1041 loadSchema: undefined, // function(uri: string): Promise {}
1042 // options to modify validated data:
1043 removeAdditional: false,
1044 useDefaults: false,
1045 coerceTypes: false,
1046 // asynchronous validation options:
1047 transpile: undefined, // requires ajv-async package
1048 // advanced options:
1049 meta: true,
1050 validateSchema: true,
1051 addUsedSchema: true,
1052 inlineRefs: true,
1053 passContext: false,
1054 loopRequired: Infinity,
1055 ownProperties: false,
1056 multipleOfPrecision: false,
1057 errorDataPath: 'object', // deprecated
1058 messages: true,
1059 sourceCode: false,
1060 processCode: undefined, // function (str: string): string {}
1061 cache: new Cache,
1062 serialize: undefined
1063}
1064```
1065
1066##### Validation and reporting options
1067
1068- _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api).
1069- _allErrors_: check all rules collecting all errors. Default is to return after the first error.
1070- _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default).
1071- _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values:
1072 - `false` (default): ignore $comment keyword.
1073 - `true`: log the keyword value to console.
1074 - function: pass the keyword value, its schema path and root schema to the specified function
1075- _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation.
1076- _uniqueItems_: validate `uniqueItems` keyword (true by default).
1077- _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.
1078- _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.
1079- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method.
1080- _unknownFormats_: handling of unknown formats. Option values:
1081 - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail.
1082 - `[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 another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail.
1083 - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification.
1084- _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object.
1085- _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. Option values:
1086 - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown.
1087 - `false` - logging is disabled.
1088
1089
1090##### Referenced schema options
1091
1092- _schemaId_: this option defines which keywords are used as schema URI. Option value:
1093 - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged).
1094 - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged).
1095 - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation.
1096- _missingRefs_: handling of missing referenced schemas. Option values:
1097 - `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).
1098 - `"ignore"` - to log error during compilation and always pass validation.
1099 - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked.
1100- _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values:
1101 - `"ignore"` (default) - 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.
1102 - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing.
1103 - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0).
1104- _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation).
1105
1106
1107##### Options to modify validated data
1108
1109- _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:
1110 - `false` (default) - not to remove additional properties
1111 - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them).
1112 - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed.
1113 - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema).
1114- _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:
1115 - `false` (default) - do not use defaults
1116 - `true` - insert defaults by value (safer and slower, object literal is used).
1117 - `"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.
1118- _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:
1119 - `false` (default) - no type coercion.
1120 - `true` - coerce scalar data types.
1121 - `"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).
1122
1123
1124##### Asynchronous validation options
1125
1126- _transpile_: Requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values:
1127 - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported.
1128 - `true` - always transpile with nodent.
1129 - `false` - do not transpile; if async functions are not supported an exception will be thrown.
1130
1131
1132##### Advanced options
1133
1134- _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). 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.
1135- _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values:
1136 - `true` (default) - if the validation fails, throw the exception.
1137 - `"log"` - if the validation fails, log error.
1138 - `false` - skip schema validation.
1139- _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `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.
1140- _inlineRefs_: Affects compilation of referenced schemas. Option values:
1141 - `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.
1142 - `false` - to not inline referenced schemas (they will be compiled as separate functions).
1143 - integer number - to limit the maximum number of keywords of the schema that will be inlined.
1144- _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.
1145- _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.
1146- _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.
1147- _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).
1148- _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`.
1149- _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)).
1150- _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call).
1151- _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options:
1152 - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass `require('js-beautify').js_beautify`.
1153 - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/epoberezkin/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information.
1154- _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()`.
1155- _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used.
1156
1157
1158## Validation errors
1159
1160In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property.
1161
1162
1163### Error objects
1164
1165Each error is an object with the following properties:
1166
1167- _keyword_: validation keyword.
1168- _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"`).
1169- _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation.
1170- _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.
1171- _message_: the standard error message (can be excluded with option `messages` set to false).
1172- _schema_: the schema of the keyword (added with `verbose` option).
1173- _parentSchema_: the schema containing the keyword (added with `verbose` option)
1174- _data_: the data validated by the keyword (added with `verbose` option).
1175
1176__Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`.
1177
1178
1179### Error parameters
1180
1181Properties of `params` object in errors depend on the keyword that failed validation.
1182
1183- `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword).
1184- `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false).
1185- `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords).
1186- `dependencies` - properties:
1187 - `property` (dependent property),
1188 - `missingProperty` (required missing dependency - only the first one is reported currently)
1189 - `deps` (required dependencies, comma separated list as a string),
1190 - `depsCount` (the number of required dependencies).
1191- `format` - property `format` (the schema of the keyword).
1192- `maximum`, `minimum` - properties:
1193 - `limit` (number, the schema of the keyword),
1194 - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`),
1195 - `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 "<", "<=", ">", ">=")
1196- `multipleOf` - property `multipleOf` (the schema of the keyword)
1197- `pattern` - property `pattern` (the schema of the keyword)
1198- `required` - property `missingProperty` (required property that is missing).
1199- `propertyNames` - property `propertyName` (an invalid property name).
1200- `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property).
1201- `type` - property `type` (required type(s), a string, can be a comma-separated list)
1202- `uniqueItems` - properties `i` and `j` (indices of duplicate items).
1203- `const` - property `allowedValue` pointing to the value (the schema of the keyword).
1204- `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword).
1205- `$ref` - property `ref` with the referenced schema URI.
1206- `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes).
1207- custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name).
1208
1209
1210## Plugins
1211
1212Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions:
1213
1214- it exports a function
1215- this function accepts ajv instance as the first parameter and returns the same instance to allow chaining
1216- this function can accept an optional configuration as the second parameter
1217
1218If you have published a useful plugin please submit a PR to add it to the next section.
1219
1220
1221## Related packages
1222
1223- [ajv-async](https://github.com/epoberezkin/ajv-async) - plugin to configure async validation mode
1224- [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats
1225- [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface
1226- [ajv-errors](https://github.com/epoberezkin/ajv-errors) - plugin for custom error messages
1227- [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) - internationalised error messages
1228- [ajv-istanbul](https://github.com/epoberezkin/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas
1229- [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - plugin with custom validation keywords (if/then/else, select, typeof, etc.)
1230- [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - plugin with keywords $merge and $patch
1231- [ajv-pack](https://github.com/epoberezkin/ajv-pack) - produces a compact module exporting validation functions
1232
1233
1234## Some packages using Ajv
1235
1236- [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser
1237- [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services
1238- [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
1239- [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator
1240- [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org
1241- [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com
1242- [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js
1243- [table](https://github.com/gajus/table) - formats data into a string table
1244- [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser
1245- [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
1246- [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
1247- [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation
1248- [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages
1249- [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema
1250- [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests
1251- [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema
1252- [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file
1253- [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app
1254- [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter
1255- [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages
1256- [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX
1257
1258
1259## Tests
1260
1261```
1262npm install
1263git submodule update --init
1264npm test
1265```
1266
1267## Contributing
1268
1269All 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.
1270
1271`npm run build` - compiles templates to [dotjs](https://github.com/epoberezkin/ajv/tree/master/lib/dotjs) folder.
1272
1273`npm run watch` - automatically compiles templates when files in dot folder change
1274
1275Please see [Contributing guidelines](https://github.com/epoberezkin/ajv/blob/master/CONTRIBUTING.md)
1276
1277
1278## Changes history
1279
1280See https://github.com/epoberezkin/ajv/releases
1281
1282__Please note__: [Changes in version 6.0.0](https://github.com/epoberezkin/ajv/releases/tag/v6.0.0).
1283
1284[Version 5.0.0](https://github.com/epoberezkin/ajv/releases/tag/5.0.0).
1285
1286[Version 4.0.0](https://github.com/epoberezkin/ajv/releases/tag/4.0.0).
1287
1288[Version 3.0.0](https://github.com/epoberezkin/ajv/releases/tag/3.0.0).
1289
1290[Version 2.0.0](https://github.com/epoberezkin/ajv/releases/tag/2.0.0).
1291
1292
1293## License
1294
1295[MIT](https://github.com/epoberezkin/ajv/blob/master/LICENSE)