aboutsummaryrefslogtreecommitdiff
path: root/node_modules/ajv/README.md
diff options
context:
space:
mode:
Diffstat (limited to 'node_modules/ajv/README.md')
-rw-r--r--node_modules/ajv/README.md203
1 files changed, 142 insertions, 61 deletions
diff --git a/node_modules/ajv/README.md b/node_modules/ajv/README.md
index 4f69fc1d6..fdf6144a2 100644
--- a/node_modules/ajv/README.md
+++ b/node_modules/ajv/README.md
@@ -2,18 +2,21 @@
# Ajv: Another JSON Schema Validator
-The fastest JSON Schema validator for node.js and browser with draft 6 support.
+The fastest JSON Schema validator for Node.js and browser with draft 6 support.
[![Build Status](https://travis-ci.org/epoberezkin/ajv.svg?branch=master)](https://travis-ci.org/epoberezkin/ajv)
[![npm version](https://badge.fury.io/js/ajv.svg)](https://www.npmjs.com/package/ajv)
+[![npm@beta](https://img.shields.io/npm/v/ajv/beta.svg)](https://github.com/epoberezkin/ajv/tree/beta)
[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv)
-[![Code Climate](https://codeclimate.com/github/epoberezkin/ajv/badges/gpa.svg)](https://codeclimate.com/github/epoberezkin/ajv)
[![Coverage Status](https://coveralls.io/repos/epoberezkin/ajv/badge.svg?branch=master&service=github)](https://coveralls.io/github/epoberezkin/ajv?branch=master)
[![Greenkeeper badge](https://badges.greenkeeper.io/epoberezkin/ajv.svg)](https://greenkeeper.io/)
[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
+__Please note__: Ajv [version 6](https://github.com/epoberezkin/ajv/tree/beta) with [JSON Schema draft-07](http://json-schema.org/work-in-progress) support is released. Use `npm install ajv@beta` to install.
+
+
## Using version 5
[JSON Schema draft-06](https://trac.tools.ietf.org/html/draft-wright-json-schema-validation-01) is published.
@@ -38,6 +41,7 @@ ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
- Validation
- [Keywords](#validation-keywords)
- [Formats](#formats)
+ - [Combining schemas with $ref](#ref)
- [$data reference](#data-reference)
- NEW: [$merge and $patch keywords](#merge-and-patch-keywords)
- [Defining custom keywords](#defining-custom-keywords)
@@ -68,7 +72,7 @@ Currently Ajv is the fastest and the most standard compliant validator according
- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html)
-Performace of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark):
+Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark):
[![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)
@@ -82,7 +86,7 @@ Performace of different validators by [json-schema-benchmark](https://github.com
- correct string lengths for strings with unicode pairs (can be turned off)
- [formats](#formats) defined by JSON Schema draft 4 standard and custom formats (can be turned off)
- [validates schemas against meta-schema](#api-validateschema)
-- supports [browsers](#using-in-browser) and nodejs 0.10-7.x
+- supports [browsers](#using-in-browser) and Node.js 0.10-8.x
- [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation
- "All errors" validation mode with [option allErrors](#options)
- [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages
@@ -106,10 +110,16 @@ Currently Ajv is the only validator that passes all the tests from [JSON Schema
npm install ajv
```
+or to install [version 6](https://github.com/epoberezkin/ajv/tree/beta):
+
+```
+npm install ajv@beta
+```
+
## <a name="usage"></a>Getting started
-Try it in the node REPL: https://tonicdev.com/npm/ajv
+Try it in the Node.js REPL: https://tonicdev.com/npm/ajv
The fastest validation call:
@@ -135,19 +145,19 @@ or
```javascript
// ...
-ajv.addSchema(schema, 'mySchema');
-var valid = ajv.validate('mySchema', data);
+var valid = ajv.addSchema(schema, 'mySchema')
+ .validate('mySchema', data);
if (!valid) console.log(ajv.errorsText());
// ...
```
See [API](#api) and [Options](#options) for more details.
-Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [json-stable-stringify](https://github.com/substack/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.
+Ajv 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.
The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call).
-__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)
+__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)
## Using in browser
@@ -161,7 +171,7 @@ Then you need to load Ajv in the browser:
<script src="ajv.min.js"></script>
```
-This bundle can be used with different module systems or creates global `Ajv` if no module system is found.
+This bundle can be used with different module systems; it creates global `Ajv` if no module system is found.
The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv).
@@ -196,7 +206,7 @@ Ajv supports all validation keywords from draft 4 of JSON-schema standard:
- [for numbers](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf
- [for strings](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format
- [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)
-- [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)
+- [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)
- [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)
- [compound keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf
@@ -232,11 +242,63 @@ There are two modes of format validation: `fast` and `full`. This mode affects f
You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method.
-The option `unknownFormats` allows to change the behaviour in case an unknown format is encountered - 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.
+The 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.
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).
+## <a name="ref"></a>Combining schemas with $ref
+
+You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword.
+
+Example:
+
+```javascript
+var schema = {
+ "$id": "http://example.com/schemas/schema.json",
+ "type": "object",
+ "properties": {
+ "foo": { "$ref": "defs.json#/definitions/int" },
+ "bar": { "$ref": "defs.json#/definitions/str" }
+ }
+};
+
+var defsSchema = {
+ "$id": "http://example.com/schemas/defs.json",
+ "definitions": {
+ "int": { "type": "integer" },
+ "str": { "type": "string" }
+ }
+};
+```
+
+Now to compile your schema you can either pass all schemas to Ajv instance:
+
+```javascript
+var ajv = new Ajv({schemas: [schema, defsSchema]});
+var validate = ajv.getSchema('http://example.com/schemas/schema.json');
+```
+
+or use `addSchema` method:
+
+```javascript
+var ajv = new Ajv;
+var validate = ajv.addSchema(defsSchema)
+ .compile(schema);
+```
+
+See [Options](#options) and [addSchema](#api) method.
+
+__Please note__:
+- `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example).
+- References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.).
+- 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.
+- The actual location of the schema file in the file system is not used.
+- 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.
+- You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown.
+- 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).
+
+
## $data reference
With `$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.
@@ -250,6 +312,8 @@ Examples.
This schema requires that the value in property `smaller` is less or equal than the value in the property larger:
```javascript
+var ajv = new Ajv({$data: true});
+
var schema = {
"properties": {
"smaller": {
@@ -264,6 +328,8 @@ var validData = {
smaller: 5,
larger: 7
};
+
+ajv.validate(schema, validData); // true
```
This schema requires that the properties have the same format as their field names:
@@ -374,14 +440,17 @@ Ajv allows defining keywords with:
Example. `range` and `exclusiveRange` keywords using compiled schema:
```javascript
-ajv.addKeyword('range', { type: 'number', compile: function (sch, parentSchema) {
- var min = sch[0];
- var max = sch[1];
+ajv.addKeyword('range', {
+ type: 'number',
+ compile: function (sch, parentSchema) {
+ var min = sch[0];
+ var max = sch[1];
- return parentSchema.exclusiveRange === true
- ? function (data) { return data > min && data < max; }
- : function (data) { return data >= min && data <= max; }
-} });
+ return parentSchema.exclusiveRange === true
+ ? function (data) { return data > min && data < max; }
+ : function (data) { return data >= min && data <= max; }
+ }
+});
var schema = { "range": [2, 4], "exclusiveRange": true };
var validate = ajv.compile(schema);
@@ -424,9 +493,9 @@ __Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"
## Asynchronous validation
-Example in node REPL: https://tonicdev.com/esp/ajv-asynchronous-validation
+Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation
-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)).
+You 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)).
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.
@@ -434,17 +503,17 @@ __Please note__: all asynchronous subschemas that are referenced from the curren
Validation 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). Ajv compiles asynchronous schemas to either [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent) or with [regenerator](https://github.com/facebook/regenerator) or to [generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) that can be optionally transpiled with regenerator as well. You can also supply any other transpiler as a function. See [Options](#options).
-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.
+The 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.
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).
-Async functions are currently supported in Chrome 55, Firefox 52, Node 7 (with --harmony-async-await) and MS Edge 13 (with flag).
+Async functions are currently supported in Chrome 55, Firefox 52, Node.js 7 (with --harmony-async-await) and MS Edge 13 (with flag).
-Generator functions are currently supported in Chrome, Firefox and node.js.
+Generator functions are currently supported in Chrome, Firefox and Node.js.
-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.
+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.
-Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that has the array of validation errors in `errors` property.
+Validation 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.
Example:
@@ -498,7 +567,7 @@ var schema = {
var validate = ajv.compile(schema);
-validate({ userId: 1, postId: 19 }))
+validate({ userId: 1, postId: 19 })
.then(function (data) {
console.log('Data is valid', data); // { userId: 1, postId: 19 }
})
@@ -507,10 +576,9 @@ validate({ userId: 1, postId: 19 }))
// data is invalid
console.log('Validation errors:', err.errors);
});
-
```
-### Using transpilers with asyncronous validation functions.
+### Using transpilers with asynchronous validation functions.
To use a transpiler you should separately install it (or load its bundle in the browser).
@@ -564,13 +632,13 @@ See [Options](#options).
|es7.regenerator|1.0|2.7|1109Kb|
|regenerator|1.0|3.2|1109Kb|
-\* Relative performance in node v.7, smaller is better.
+\* Relative performance in Node.js 7.x — smaller is better.
[nodent](https://github.com/MatAtBread/nodent) has several advantages:
- much smaller browser bundle than regenerator
-- almost the same performance of generated code as native generators in nodejs and the latest Chrome
-- much better performace than native generators in other browsers
+- almost the same performance of generated code as native generators in Node.js and the latest Chrome
+- much better performance than native generators in other browsers
- works in IE 9 (regenerator does not)
@@ -823,13 +891,13 @@ Unless the option `validateSchema` is false, the schema will be validated agains
##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -&gt; Promise
-Asyncronous 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 callback if passed will be called with an error) when:
+Asynchronous 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:
-- missing schema can't be loaded (`loadSchema` returns the Promise that rejects).
-- the schema containing missing reference is loaded, but the reference cannot be resolved.
-- schema (or some referenced schema) is invalid.
+- missing schema can't be loaded (`loadSchema` returns a Promise that rejects).
+- a schema containing a missing reference is loaded, but the reference cannot be resolved.
+- schema (or some loaded/referenced schema) is invalid.
-The function compiles schema and loads the first missing schema (or meta-schema), until all missing schemas are loaded.
+The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded.
You can asynchronously compile meta-schema by passing `true` as the second parameter.
@@ -849,7 +917,7 @@ __Please note__: every time this method is called the errors are overwritten so
If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation).
-##### .addSchema(Array&lt;Object&gt;|Object schema [, String key])
+##### .addSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv
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.
@@ -864,8 +932,14 @@ Although `addSchema` does not compile schemas, explicit compilation is not requi
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.
+__Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`.
+This allows you to do nice things like the following.
+
+```javascript
+var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri);
+```
-##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key])
+##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv
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).
@@ -878,19 +952,19 @@ Validates schema. This method should be used to validate schemas rather than `va
By default this method is called automatically when the schema is added, so you rarely need to use it directly.
-If schema doesn't have `$schema` property it is validated against draft 6 meta-schema (option `meta` should not be false).
+If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false).
-If schema has `$schema` property then the schema with this id (that should be previously added) is used to validate passed schema.
+If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema.
Errors will be available at `ajv.errors`.
##### .getSchema(String key) -&gt; Function&lt;Object data&gt;
-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.
+Retrieve 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.
-##### .removeSchema([Object schema|String key|String ref|RegExp pattern])
+##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -&gt; Ajv
Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references.
@@ -903,7 +977,7 @@ Schema can be removed using:
If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared.
-##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format)
+##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format) -&gt; Ajv
Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance.
@@ -921,7 +995,7 @@ If object is passed it should have properties `validate`, `compare` and `async`:
Custom formats can be also added via `formats` option.
-##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition)
+##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition) -&gt; Ajv
Add custom validation keyword to Ajv instance.
@@ -962,7 +1036,7 @@ See [Defining custom keywords](#defining-custom-keywords) for more details.
Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown.
-##### .removeKeyword(String keyword)
+##### .removeKeyword(String keyword) -&gt; Ajv
Removes custom or pre-defined keyword so you can redefine them.
@@ -995,6 +1069,7 @@ Defaults:
formats: {},
unknownFormats: true,
schemas: {},
+ logger: undefined,
// referenced schema options:
schemaId: undefined // recommended '$id'
missingRefs: true,
@@ -1030,7 +1105,7 @@ Defaults:
- _$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).
- _allErrors_: check all rules collecting all errors. Default is to return after the first error.
- _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default).
-- _jsonPointers_: set `dataPath` propery of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation.
+- _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation.
- _uniqueItems_: validate `uniqueItems` keyword (true by default).
- _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.
- _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.
@@ -1039,7 +1114,10 @@ Defaults:
- `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.
- `[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.
- `"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.
-- _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.
+- _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.
+- _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. Option values:
+ - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown.
+ - `false` - logging is disabled.
##### Referenced schema options
@@ -1054,7 +1132,7 @@ Defaults:
- `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked.
- _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values:
- `"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.
- - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recomended to make sure schema has no keywords that are ignored, which can be confusing.
+ - `"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.
- `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0).
- _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).
@@ -1080,12 +1158,12 @@ Defaults:
- _async_: determines how Ajv compiles asynchronous schemas (see [Asynchronous validation](#asynchronous-validation)) to functions. Option values:
- `"*"` / `"co*"` (default) - compile to generator function ("co*" - wrapped with `co.wrap`). If generators are not supported and you don't provide `processCode` option (or `transpile` option if you use [ajv-async](https://github.com/epoberezkin/ajv-async) package), the exception will be thrown when async schema is compiled.
- - `"es7"` - compile to es7 async function. Unless your platform supports them you need to provide `processCode`/`transpile` option. According to [compatibility table](http://kangax.github.io/compat-table/es7/)) async functions are supported by:
+ - `"es7"` - compile to es7 async function. Unless your platform supports them you need to provide `processCode` or `transpile` option. According to [compatibility table](http://kangax.github.io/compat-table/es7/)) async functions are supported by:
- Firefox 52,
- Chrome 55,
- Node.js 7 (with `--harmony-async-await`),
- MS Edge 13 (with flag).
- - `undefined`/`true` - auto-detect async mode. It requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. If transpile option is not passed ajv-async will choose the first of supported/installed async/transpile modes in this order:
+ - `undefined`/`true` - auto-detect async mode. It requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. If `transpile` option is not passed, ajv-async will choose the first of supported/installed async/transpile modes in this order:
- "es7" (native async functions),
- "co*" (native generators with co.wrap),
- "es7"/"nodent",
@@ -1119,14 +1197,14 @@ Defaults:
- _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call).
- _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:
- `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`.
- - `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.
+ - `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.
- _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()`.
-- _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 [json-stable-stringify](https://github.com/substack/json-stable-stringify) is used.
+- _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.
## Validation errors
-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` property.
+In 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.
### Error objects
@@ -1156,7 +1234,7 @@ Properties of `params` object in errors depend on the keyword that failed valida
- `property` (dependent property),
- `missingProperty` (required missing dependency - only the first one is reported currently)
- `deps` (required dependencies, comma separated list as a string),
- - `depsCount` (the number of required dependedncies).
+ - `depsCount` (the number of required dependencies).
- `format` - property `format` (the schema of the keyword).
- `maximum`, `minimum` - properties:
- `limit` (number, the schema of the keyword),
@@ -1176,11 +1254,14 @@ Properties of `params` object in errors depend on the keyword that failed valida
## Related packages
-- [ajv-cli](https://github.com/epoberezkin/ajv-cli) - command line interface for Ajv
+- [ajv-async](https://github.com/epoberezkin/ajv-async) - configure async validation mode
+- [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface
+- [ajv-errors](https://github.com/epoberezkin/ajv-errors) - custom error messages
- [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) - internationalised error messages
-- [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - keywords $merge and $patch.
-- [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - several custom keywords that can be used with Ajv (typeof, instanceof, range, propertyNames)
-- [ajv-errors](https://github.com/epoberezkin/ajv-errors) - custom error messages for Ajv
+- [ajv-istanbul](https://github.com/epoberezkin/ajv-istanbul) - instrument generated validation code to measure test coverage of your schemas
+- [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - custom validation keywords (if/then/else, select, typeof, etc.)
+- [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - keywords $merge and $patch
+- [ajv-pack](https://github.com/epoberezkin/ajv-pack) - produces a compact module exporting validation functions
## Some packages using Ajv
@@ -1191,7 +1272,7 @@ Properties of `params` object in errors depend on the keyword that failed valida
- [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator
- [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org
- [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON-schema http://jsonschemalint.com
-- [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for node.js
+- [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js
- [table](https://github.com/gajus/table) - formats data into a string table
- [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser
- [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
@@ -1202,7 +1283,7 @@ Properties of `params` object in errors depend on the keyword that failed valida
- [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON-schema with expect in mocha tests
- [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema
- [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file
-- [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app
+- [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app
- [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter
- [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages