The fastest JSON Schema validator for node.js and browser. Supports v5 proposals.
- Performance
- Features
- Getting started
- Frequently Asked Questions
- Using in browser
- Command line interface
- Validation
- Modifying data during validation
- API
- Packages using Ajv
- Tests, Contributing, History, License
Ajv generates code using doT templates to turn JSON schemas into super-fast validation functions that are efficient for v8 optimization.
Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks:
- json-schema-benchmark - 50% faster than the second place
- jsck benchmark - 20-190% faster
- z-schema benchmark
- themis benchmark
Performace of different validators by json-schema-benchmark:
- Ajv implements full JSON Schema draft 4 standard:
- all validation keywords (see JSON-Schema validation keywords)
- full support of remote refs (remote schemas have to be added with
addSchema
or compiled to be available) - support of circular references between schemas
- correct string lengths for strings with unicode pairs (can be turned off)
- formats defined by JSON Schema draft 4 standard and custom formats (can be turned off)
- validates schemas against meta-schema
- supports browsers and nodejs 0.10-5.0
- asynchronous loading of referenced schemas during compilation
- "All errors" validation mode with option allErrors
- error messages with parameters describing error reasons to allow creating custom error messages
- i18n error messages support with ajv-i18n package (version >= 1.0.0)
- filtering data from additional properties
- assigning defaults to missing properties and items
- coercing data to the types specified in
type
keywords - custom keywords
- keywords
switch
,constant
,contains
,patternGroups
,patternRequired
,formatMaximum
/formatMinimum
andformatExclusiveMaximum
/formatExclusiveMinimum
from JSON-schema v5 proposals with option v5 - v5 meta-schema for schemas using v5 keywords
- v5 $data reference to use values from the validated data as values for the schema keywords
- asynchronous validation of custom formats and keywords
Currently Ajv is the only validator that passes all the tests from JSON Schema Test Suite (according to json-schema-benchmark, apart from the test that requires that 1.0
is not an integer that is impossible to satisfy in JavaScript).
npm install ajv
Try it in the node REPL: https://tonicdev.com/npm/ajv
The fastest validation call:
var Ajv = require('ajv');
var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
var validate = ajv.compile(schema);
var valid = validate(data);
if (!valid) console.log(validate.errors);
or with less code
// ...
var valid = ajv.validate(schema, data);
if (!valid) console.log(ajv.errors);
// ...
or
// ...
ajv.addSchema(schema, 'mySchema');
var valid = ajv.validate('mySchema', data);
if (!valid) console.log(ajv.errorsText());
// ...
See API and Options for more details.
Ajv compiles schemas to functions and caches them in all cases (using schema stringified with json-stable-stringify as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again.
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
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 UMD bundle using npm run bundle
script (thanks to siddo420).
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.
The browser bundle is available on cdnjs.
Ajv is tested with these browsers:
Please note: some frameworks, e.g. Dojo, may redifine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue #234).
CLI is available as a separate npm package ajv-cli. It supports:
- compiling JSON-schemas to test their validity
- validating data file(s) against JSON-schema
- testing expected validity of data against JSON-schema
- referenced schemas
- custom meta-schemas
- files in JSON and JavaScript format
- all Ajv options
- reporting changes in data after validation in JSON-patch format
Ajv supports all validation keywords from draft 4 of JSON-schema standard:
- type
- for numbers - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf
- for strings - maxLength, minLength, pattern, format
- for arrays - maxItems, minItems, uniqueItems, items, additionalItems
- for objects - maxProperties, minproperties, required, properties, patternProperties, additionalProperties, dependencies
- compound keywords - enum, not, oneOf, anyOf, allOf
With option v5: true
Ajv also supports all validation keywords and $data reference from v5 proposals for JSON-schema standard:
- switch - conditional validation with a sequence of if/then clauses
- contains - check that array contains a valid item
- constant - check that data is equal to some value
- patternGroups - a more powerful alternative to patternProperties
- patternRequired - like
required
but with patterns that some property should match. - formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum - setting limits for date, time, etc.
See JSON-Schema validation keywords for more details.
The following formats are supported for string validation with "format" keyword:
- date: full-date according to RFC3339.
- time: time with optional time-zone.
- date-time: date-time from the same source (time-zone is mandatory).
date
,time
anddate-time
validate ranges infull
mode and only regexp infast
mode (see options). - uri: full uri with optional protocol.
- email: email address.
- hostname: host name acording to RFC1034.
- ipv4: IP address v4.
- ipv6: IP address v6.
- regex: tests whether a string is a valid regular expression by passing it to RegExp constructor.
- uuid: Universally Unique IDentifier according to RFC4122.
- json-pointer: JSON-pointer according to RFC6901.
- relative-json-pointer: relative JSON-pointer according to this draft.
There are two modes of format validation: fast
and full
. This mode affects formats date
, time
, date-time
, uri
, email
, and hostname
. See Options for details.
You can add additional formats and replace any of the formats above using addFormat method.
You can find patterns used for format validation and the sources that were used in formats.js.
With v5
option you can use values from the validated data as the values for the schema keywords. See v5 proposal for more information about how it works.
$data
reference is supported in the keywords: constant, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems.
The value of "$data" should be a JSON-pointer 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 (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).
Examples.
This schema requires that the value in property smaller
is less or equal than the value in the property larger:
var schema = {
"properties": {
"smaller": {
"type": "number",
"maximum": { "$data": "1/larger" }
},
"larger": { "type": "number" }
}
};
var validData = {
smaller: 5,
larger: 7
};
This schema requires that the properties have the same format as their field names:
var schema = {
"additionalProperties": {
"type": "string",
"format": { "$data": "0#" }
}
};
var validData = {
'date-time': '1963-06-19T08:30:06.283185Z',
email: 'joe.bloggs@example.com'
}
$data
reference is resolved safely - it won't throw even if some property is undefined. If $data
resolves to undefined
the validation succeeds (with the exclusion of constant
keyword). If $data
resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails.
With v5 option and the package 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) and JSON Patch (RFC 6902).
To add keywords $merge
and $patch
to Ajv instance use this code:
require('ajv-merge-patch')(ajv);
Examples.
Using $merge
:
{
"$merge": {
"source": {
"type": "object",
"properties": { "p": { "type": "string" } },
"additionalProperties": false
},
"with": {
"properties": { "q": { "type": "number" } }
}
}
}
Using $patch
:
{
"$patch": {
"source": {
"type": "object",
"properties": { "p": { "type": "string" } },
"additionalProperties": false
},
"with": [
{ "op": "add", "path": "/properties/q", "value": { "type": "number" } }
]
}
}
The schemas above are equivalent to this schema:
{
"type": "object",
"properties": {
"p": { "type": "string" },
"q": { "type": "number" }
},
"additionalProperties": false
}
The properties source
and with
in the keywords $merge
and $patch
can use absolute or relative $ref
to point to other schemas previously added to the Ajv instance or to the fragments of the current schema.
See the package ajv-merge-patch for more information.
Starting from version 2.0.0 ajv supports custom keyword definitions.
The advantages of using custom keywords are:
- allow creating validation scenarios that cannot be expressed using JSON-Schema
- simplify your schemas
- help bringing a bigger part of the validation logic to your schemas
- make your schemas more expressive, less verbose and closer to your application domain
- implement custom data processors that modify your data and/or create side effects while the data is being validated
The concerns you have to be aware of when extending JSON-schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas.
You can define custom keywords with addKeyword method. Keywords are defined on the ajv
instance level - new instances will not have previously defined keywords.
Ajv allows defining keywords with:
- validation function
- compilation function
- macro function
- inline compilation function that should return code (as string) that will be inlined in the currently compiled schema.
Example. range
and exclusiveRange
keywords using compiled schema:
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; }
} });
var schema = { "range": [2, 4], "exclusiveRange": true };
var validate = ajv.compile(schema);
console.log(validate(2.01)); // true
console.log(validate(3.99)); // true
console.log(validate(2)); // false
console.log(validate(4)); // false
See Defining custom keywords for details.
During asynchronous compilation remote references are loaded using supplied function. See compileAsync
method and loadSchema
option.
Example:
var ajv = new Ajv({ loadSchema: loadSchema });
ajv.compileAsync(schema, function (err, validate) {
if (err) return;
var valid = validate(data);
});
function loadSchema(uri, callback) {
request.json(uri, function(err, res, body) {
if (err || res.statusCode >= 400)
callback(err || new Error('Loading error: ' + res.statusCode));
else
callback(null, body);
});
}
Please note: Option missingRefs
should NOT be set to "ignore"
or "fail"
for asynchronous compilation to work.
Example in node REPL: https://tonicdev.com/esp/ajv-asynchronous-validation
Starting from version 3.5.0 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, addKeyword and 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.
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.
Validation function for an asynchronous custom format/keyword should return a promise that resolves to true
or false
(or rejects with new Ajv.ValidationError(errors)
if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to either generator function (default) that can be optionally transpiled with regenerator or to es7 async function that can be transpiled with nodent or with regenerator as well. You can also supply any other transpiler as a function. See 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.
If you are using generators, the compiled validation function can be either wrapped with co (default) or returned as generator function, that can be used directly, e.g. in koa 1.0. co
is a small library, it is included in Ajv (both as npm dependency and in the browser bundle).
Generator functions are currently supported in Chrome, Firefox and node.js (0.11+); if you are using Ajv in other browsers or in older versions of node.js you should use one of available transpiling options. All provided async modes use global Promise class. If your platform does not have Promise you should use a polyfill that defines it.
Validation result will be a promise that resolves to true
or rejects with an exception Ajv.ValidationError
that has the array of validation errors in errors
property.
Example:
/**
* without "async" and "transpile" options (or with option {async: true})
* Ajv will choose the first supported/installed option in this order:
* 1. native generator function wrapped with co
* 2. es7 async functions transpiled with nodent
* 3. es7 async functions transpiled with regenerator
*/
var ajv = new Ajv;
ajv.addKeyword('idExists', {
async: true,
type: 'number',
validate: checkIdExists
});
function checkIdExists(schema, data) {
return knex(schema.table)
.select('id')
.where('id', data)
.then(function (rows) {
return !!rows/length; // true if record is found
});
}
var schema = {
"$async": true,
"properties": {
"userId": {
"type": "integer",
"idExists": { "table": "users" }
},
"postId": {
"type": "integer",
"idExists": { "table": "posts" }
}
}
};
var validate = ajv.compile(schema);
validate({ userId: 1, postId: 19 }))
.then(function (valid) {
// "valid" is always true here
console.log('Data is valid');
})
.catch(function (err) {
if (!(err instanceof Ajv.ValidationError)) throw err;
// data is invalid
console.log('Validation errors:', err.errors);
});
To use a transpiler you should separately install it (or load its bundle in the browser).
Ajv npm package includes minified browser bundles of regenerator and nodent in dist folder.
var ajv = new Ajv({ /* async: 'es7', */ transpile: 'nodent' });
var validate = ajv.compile(schema); // transpiled es7 async function
validate(data).then(successFunc).catch(errorFunc);
npm install nodent
or use nodent.min.js
from dist folder of npm package.
var ajv = new Ajv({ /* async: 'es7', */ transpile: 'regenerator' });
var validate = ajv.compile(schema); // transpiled es7 async function
validate(data).then(successFunc).catch(errorFunc);
npm install regenerator
or use regenerator.min.js
from dist folder of npm package.
var ajv = new Ajv({ async: 'es7', transpile: transpileFunc });
var validate = ajv.compile(schema); // transpiled es7 async function
validate(data).then(successFunc).catch(errorFunc);
See Options.
mode | transpile speed* |
run-time speed* |
bundle size |
---|---|---|---|
generators (native) |
- | 1.0 | - |
es7.nodent | 1.35 | 1.1 | 183Kb |
es7.regenerator | 1.0 | 2.7 | 322Kb |
regenerator | 1.0 | 3.2 | 322Kb |
* Relative performance in node v.4, smaller is better.
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
- works in IE 9 (regenerator does not)
regenerator is a more widely adopted alternative.
With option removeAdditional
(added by andyscott) you can filter data during the validation.
This option modifies original data.
Example:
var ajv = new Ajv({ removeAdditional: true });
var schema = {
"additionalProperties": false,
"properties": {
"foo": { "type": "number" },
"bar": {
"additionalProperties": { "type": "number" },
"properties": {
"baz": { "type": "string" }
}
}
}
}
var data = {
"foo": 0,
"additional1": 1, // will be removed; `additionalProperties` == false
"bar": {
"baz": "abc",
"additional2": 2 // will NOT be removed; `additionalProperties` != false
},
}
var validate = ajv.compile(schema);
console.log(validate(data)); // true
console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 }
If removeAdditional
option in the example above were "all"
then both additional1
and additional2
properties would have been removed.
If the option were "failing"
then property additional1
would have been removed regardless of its value and property additional2
would have been removed only if its value were failing the schema in the inner additionalProperties
(so in the example above it would have stayed because it passes the schema, but any non-number would have been removed).
Please note: If you use removeAdditional
option with additionalProperties
keyword inside anyOf
/oneOf
keywords your validation can fail with this schema, for example:
{
"type": "object",
"oneOf": [
{
"properties": {
"foo": { "type": "string" }
},
"required": [ "foo" ],
"additionalProperties": false
},
{
"properties": {
"bar": { "type": "integer" }
},
"required": [ "bar" ],
"additionalProperties": false
}
]
}
The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties.
With the option removeAdditional: true
the validation will pass for the object { "foo": "abc"}
but will fail for the object {"bar": 1}
. It happens because while the first subschema in oneOf
is validated, the property bar
is removed because it is an additional property according to the standard (because it is not included in properties
keyword in the same schema).
While this behaviour is unexpected (issues #129, #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:
< 10000 div class="highlight highlight-source-json notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="{ "type": "object", "properties": { "foo": { "type": "string" }, "bar": { "type": "integer" } }, "additionalProperties": false, "oneOf": [ { "required": [ "foo" ] }, { "required": [ "bar" ] } ] }">{ "type": "object", "properties": { "foo": { "type": "string" }, "bar": { "type": "integer" } }, "additionalProperties": false, "oneOf": [ { "required": [ "foo" ] }, { "required": [ "bar" ] } ] }