ajv/README.md

317 lines
14 KiB
Markdown
Raw Normal View History

2015-06-07 23:59:04 +03:00
# ajv - Another JSON Schema Validator
2015-05-20 03:55:53 +03:00
One of the fastest JSON Schema validators for node.js and browser.
It uses precompiled [doT templates](https://github.com/olado/doT) to generate super-fast validating functions.
2015-06-13 12:42:55 +03:00
[![Build Status](https://travis-ci.org/epoberezkin/ajv.svg?branch=master)](https://travis-ci.org/epoberezkin/ajv)
2015-06-14 13:40:24 +03:00
[![npm version](https://badge.fury.io/js/ajv.svg)](http://badge.fury.io/js/ajv)
2015-07-21 21:06:42 +03:00
[![Code Climate](https://codeclimate.com/github/epoberezkin/ajv/badges/gpa.svg)](https://codeclimate.com/github/epoberezkin/ajv)
2015-06-18 16:59:11 +03:00
2015-06-07 23:59:04 +03:00
## JSON Schema standard
2015-06-07 23:55:40 +03:00
2015-06-07 23:59:04 +03:00
ajv implements full [JSON Schema draft 4](http://json-schema.org/) standard:
2015-06-07 23:55:40 +03:00
- all validation keywords
2015-06-08 02:19:34 +03:00
- full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available)
2015-07-04 03:58:08 +03:00
- support of circular dependencies between schemas
2015-06-07 23:55:40 +03:00
- correct string lengths for strings with unicode pairs (can be turned off)
2015-06-15 03:01:59 +03:00
- formats defined by JSON Schema draft 4 standard and custom formats (can be turned off)
2015-06-07 23:55:40 +03:00
ajv passes all the tests from [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (apart from the one that requires that `1.0` is not an integer).
2015-06-15 10:00:40 +03:00
## Benchmarks
Benchmark of the test suite - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark).
[Same benchmark](https://github.com/epoberezkin/json-schema-benchmark) run on faster CPU with node 0.12.
[Benchmark of individual test cases](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) by [z-schema](https://github.com/zaggino/z-schema).
2015-05-30 01:22:11 +03:00
## Install
```
2015-05-30 01:32:47 +03:00
npm install ajv
2015-05-30 01:22:11 +03:00
```
## Usage
2015-08-08 12:55:37 +03:00
The fastest validation call:
2015-05-30 01:22:11 +03:00
```
2015-06-08 02:19:34 +03:00
var Ajv = require('ajv');
var ajv = Ajv(); // options can be passed
2015-05-30 01:32:47 +03:00
var validate = ajv.compile(schema);
2015-05-30 23:08:31 +03:00
var valid = validate(data);
if (!valid) console.log(validate.errors);
2015-05-30 01:22:11 +03:00
```
2015-08-08 12:55:37 +03:00
or with less code
2015-05-30 01:22:11 +03:00
```
2015-05-30 23:08:31 +03:00
// ...
var valid = ajv.validate(schema, data);
if (!valid) console.log(ajv.errors);
2015-05-30 23:08:31 +03:00
// ...
2015-05-30 01:22:11 +03:00
```
2015-06-08 02:19:34 +03:00
or
```
// ...
ajv.addSchema(schema, 'mySchema');
var valid = ajv.validate('mySchema', data);
2015-06-17 04:05:52 +03:00
if (!valid) console.log(ajv.errorsText());
2015-06-08 02:19:34 +03:00
// ...
```
ajv compiles schemas to functions and caches them in all cases (using stringified schema as a key - using [json-stable-stringify](https://github.com/substack/json-stable-stringify)), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again.
2015-05-30 01:22:11 +03:00
2015-08-08 12:55:37 +03:00
The best performance is achieved when using compiled functions (there is no additional function call).
2015-05-30 01:22:11 +03:00
## Using in browser
You can require ajv directly from the code you browserify - in this case ajv will be a part of your bundle.
If you need to use ajv in several bundles you can create a separate browserified bundle using `bin/create-bundle` script (thanks to [siddo420](https://github.com/siddo420)).
Then you need to load ajv in the browser:
```
<script src="ajv.bundle.js"></script>
```
Now you can use it as shown above - `require` will be global and you can `require('ajv')`.
Ajv was tested with these browsers:
[![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin)
2015-07-22 00:36:20 +03:00
## Formats
The following formats are supported for string validation with "format" keyword:
- _date_: full-date from http://tools.ietf.org/html/rfc3339#section-5.6
- _date-time_: date-time from the same source. Both `date` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)).
- _uri_: full uri with optional protocol.
- _email_: email address.
- _hostname_: host name acording to http://tools.ietf.org/html/rfc1034#section-3.5
- _ipv4_: IP address v4.
- _ipv6_: IP address v6.
- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor.
There are two modes of fomat validation: `fast` and `full` that affect all formats but `ipv4` and `ipv6`. See [Options](#options) for details.
2015-07-22 01:16:02 +03:00
You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method.
2015-07-22 00:36:20 +03:00
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).
2015-07-30 11:21:36 +03:00
## Filtering data
With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation.
This option modifies original object.
2015-06-08 02:19:34 +03:00
## API
2015-06-08 02:29:04 +03:00
##### Ajv(Object options) -&gt; Object
2015-06-08 02:19:34 +03:00
Create ajv instance.
2015-06-08 09:52:51 +03:00
All the instance methods below are bound to the instance, so they can be used without the instance.
2015-06-08 02:19:34 +03:00
2015-06-08 02:29:04 +03:00
##### .compile(Object schema) -&gt; Function&lt;Object data&gt;
2015-06-08 02:19:34 +03:00
2015-06-08 09:51:34 +03:00
Generate validating function and cache the compiled schema for future use.
2015-06-08 02:19:34 +03:00
Validating function returns boolean and has properties `errors` with the errors from the last validation (`null` if there were no errors) and `schema` with the reference to the original schema.
2015-06-08 09:52:51 +03:00
2015-07-26 12:35:08 +03:00
Unless the option `validateSchema` is false, the schema will be validated against meta-schema and if schema is invalid the error will be thrown. See [options](#options).
2015-06-17 04:05:52 +03:00
2015-06-08 02:19:34 +03:00
2015-06-08 02:29:04 +03:00
##### .validate(Object schema|String key|String ref, data) -&gt; Boolean
2015-06-08 02:19:34 +03:00
Validate data using passed schema (it will be compiled and cached).
2015-06-08 09:51:34 +03:00
Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference.
2015-06-08 02:19:34 +03:00
Validation errors will be available in the `errors` property of ajv instance (`null` if there were no errors).
2015-06-08 02:19:34 +03:00
2015-07-04 03:58:08 +03:00
##### .addSchema(Array&lt;Object&gt;|Object schema [, String key])
2015-06-08 02:19:34 +03:00
2015-07-04 03:58:08 +03:00
Add schema(s) to validator instance. From version 1.0.0 this method does not compile schemas (but it still validates them). Because of that change, 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.
2015-06-08 02:19:34 +03:00
- array of schemas can be passed (schemas should have ids), the second parameter will be ignored.
- key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key.
2015-07-04 03:58:08 +03:00
Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data.
2015-06-08 02:19:34 +03:00
2015-07-04 03:58:08 +03:00
Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time.
2015-06-08 02:19:34 +03:00
2015-07-26 12:37:56 +03:00
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.
2015-08-08 12:55:37 +03:00
##### .addMetaSchema(Object schema [, String key]) -&gt; Function
Adds meta schema 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).
There is no need to explicitely add draft 4 meta schema (http://json-schema.org/draft-04/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`.
##### .validateSchema(Object schema) -&gt; Boolean
2015-06-20 16:59:06 +03:00
Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON-Schema standart.
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 4 meta-schema (option `meta` should not be false).
2015-06-20 16:59:06 +03:00
If schema has `$schema` property then the schema with this id (should be previously added) is used to validate passed schema.
2015-06-20 16:59:06 +03:00
Errors will be available at `ajv.errors`.
2015-06-08 02:19:34 +03:00
2015-06-08 02:29:04 +03:00
##### .getSchema(String key) -&gt; Function&lt;Object data&gt;
2015-06-08 02:19:34 +03:00
2015-06-20 20:40:13 +03:00
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.
##### .removeSchema(Object schema|String key|String ref)
Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references.
Schema can be removed using key passed to `addSchema`, it's full reference (id) or using actual schema object that will be stable-stringified to remove schema from cache.
2015-06-08 02:19:34 +03:00
2015-07-22 01:16:02 +03:00
##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function format)
2015-06-13 15:42:58 +03:00
Add custom format to validate strings. It can also be used to replace pre-defined formats for ajv instance.
2015-07-21 21:18:03 +03:00
Strings are converted to RegExp.
2015-06-13 15:42:58 +03:00
Function should return validation result as `true` or `false`.
Custom formats can be also added via `formats` option.
2015-07-22 00:38:13 +03:00
##### .errorsText([Array&lt;Object&gt; errors [, Object options]]) -&gt; String
2015-06-17 04:05:52 +03:00
2015-07-22 00:36:20 +03:00
Returns the text with all errors in a String.
2015-06-17 04:05:52 +03:00
2015-07-22 00:36:20 +03:00
Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default).
2015-06-17 04:05:52 +03:00
2015-05-30 01:22:11 +03:00
## Options
- _allErrors_: check all rules collecting all errors. Default is to return after the first error.
- _removeAdditional_: remove additional properties. Default is not to remove. If the option is 'all', then all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). If the option is `true` (or truthy), only additional properties with `additionalProperties` keyword equal to `false` are removed. If the option is 'failing', then additional properties that fail schema validation will be removed too (where `additionalProperties` keyword is schema).
- _verbose_: include the reference to the part of the schema and validated data in errors (false by default).
- _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.
2015-06-13 15:42:58 +03:00
- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method.
2015-06-18 16:59:11 +03:00
- _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.
- _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default).
2015-06-18 16:59:11 +03:00
- _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can either be absent (draft-4 meta-schema will be used) or can be a reference to any previously added schema. If the validation fails, the exception is thrown. Pass "log" in this option to log error instead of throwing exception. Pass `false` to skip schema validation.
- _missingRefs_: by default if the reference cannot be resolved during compilation the exception is thrown. Pass 'ignore' to log error during compilation and pass validation. Pass 'fail' to log error and successfully compile schema but fail validation if this rule is checked.
2015-06-08 02:19:34 +03:00
- _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.
- _beautify_: format the generated function with [js-beautify](https://github.com/beautify-web/js-beautify) (the validating function is generated without line-breaks). `npm install js-beautify` to use this option. `true` or js-beautify options can be passed.
2015-06-23 02:51:34 +03:00
- _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)` and `get(key)`.
2015-06-05 23:37:36 +03:00
## Tests
```
2015-07-22 01:23:37 +03:00
npm install
2015-06-05 23:37:36 +03:00
git submodule update --init
npm test
```
2015-08-01 16:26:04 +03:00
Browser:
```
bin/prepare-tests
karma start
```
## Contributing
2015-08-01 16:26:04 +03:00
All validation functions are generated using doT templates in [dot](https://github.com/epoberezkin/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency.
2015-08-01 16:26:04 +03:00
`bin/compile-dots` - compiles templates to [dotjs](https://github.com/epoberezkin/ajv/tree/master/lib/dotjs) folder (please use node 0.10 to compile - 0.12 is fully supported but it inserts some empty comments in function parameters when Function constructor is called).
2015-08-01 16:26:04 +03:00
`bin/watch-dots` - automatically compiles templates when files in dot folder change
2015-08-01 16:26:04 +03:00
`bin/git-hook` - installs symbolic link to pre-commit hook that will compile templates and run tests.
## Changes history
##### 0.6.11
Improved/fixed data filtering with `removeAdditional` option.
2015-07-30 11:21:36 +03:00
##### 0.6.10
`removeAdditional` option allowing to remove additional properties.
2015-07-04 03:58:08 +03:00
##### 1.0.0
`addSchema` no longer compiles schemas and its return value is `undefined`
Dependencies can be added in any order (all dependencies should be present when the schema is compiled though)
Circular dependencies support
##### 0.6.1
Errors for "required" keyword validation include missing properties
Better references resolution in schemas without IDs
2015-06-20 20:46:51 +03:00
##### 0.5.9
`cache` option and `removeSchema` method
##### 0.5.2
doT is no longer a run-time dependency
ajv can be used in the browser (with browserify)
2015-06-17 04:05:52 +03:00
##### 0.5.0
Schemas are validated against meta-schema before compilation
2015-06-13 15:42:58 +03:00
##### 0.4.1
Custom formats support.
##### 0.4.0
2015-06-13 15:42:58 +03:00
Errors are set to `null` if there are no errors (previously empty array).
2015-06-19 23:34:34 +03:00
## License
[MIT](https://github.com/epoberezkin/ajv/blob/master/LICENSE)