Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
The ajv npm package is a fast JSON Schema validator that allows you to validate JSON data against a JSON schema. It supports the latest JSON Schema draft-07 and has several extensions. It can be used for data validation, data sanitization, and to ensure that JSON documents comply with a predefined schema.
Validate data against a JSON Schema
This feature allows you to compile a JSON Schema and use it to validate JSON data. If the data does not conform to the schema, the errors can be logged or handled as needed.
{"const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
"type": "object",
"properties": {
"foo": {"type": "integer"},
"bar": {"type": "string"}
},
"required": ["foo"]
};
const validate = ajv.compile(schema);
const valid = validate({foo: 1, bar: 'abc'});
if (!valid) console.log(validate.errors);"}
Add custom keywords
Ajv allows you to define custom keywords for a JSON Schema, which can be used to create custom validation rules that are not defined in the JSON Schema specification.
{"const Ajv = require('ajv');
const ajv = new Ajv();
ajv.addKeyword('even', {
validate: function(schema, data) {
return data % 2 === 0;
}
});
const schema = {"even": true};
const validate = ajv.compile(schema);
const valid = validate(2); // true
const invalid = validate(3); // false"}
Asynchronous validation
Ajv supports asynchronous schema compilation, which is useful when your JSON Schema depends on other schemas that need to be fetched remotely.
{"const Ajv = require('ajv');
const ajv = new Ajv({loadSchema: loadExternalSchema});
// Assume loadExternalSchema is a function that loads a schema asynchronously
ajv.compileAsync(schema).then(function(validate) {
const valid = validate(data);
if (!valid) console.log(validate.errors);
}).catch(function(err) {
console.error('Failed to compile schema:', err);
});"}
Joi is a powerful schema description language and data validator for JavaScript. Unlike ajv, which focuses on JSON Schema, Joi allows you to create validation schemas using a fluent API. It is often used for validating data in REST APIs.
Tiny Validator (tv4) is a small and fast JSON Schema (v4) validator. It is less feature-rich compared to ajv and does not support the latest JSON Schema specifications, but it is suitable for simple validation tasks.
The jsonschema package is another validator for JSON Schema that supports draft-04/06/07. It is not as fast as ajv but provides a straightforward API for validating JSON data against schemas.
The fastest JSON Schema validator for Node.js and browser. Supports draft-06/07/2019-09 (draft-04 is supported in version 6).
Ajv version 7 (beta) is released with these changes:
unevaluatedProperties
and unevaluatedItems
, dynamic recursive references and other additional keywords.Please note:
See release notes for the details.
To install the new version:
npm install ajv@beta
See Getting started for code example.
Ajv has been awarded a grant from Mozilla’s Open Source Support (MOSS) program in the “Foundational Technology” track! It will sponsor the development of Ajv support of JSON Schema version 2019-09 and of JSON Type Definition.
Ajv also joined OpenJS Foundation – having this support will help ensure the longevity and stability of Ajv for all its users.
This blog post has more details.
I am looking for the long term maintainers of Ajv – working with ReadySet, also sponsored by Mozilla, to establish clear guidelines for the role of a "maintainer" and the contribution standards, and to encourage a wider, more inclusive, contribution from the community.
Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant!
Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released.
Please sponsor Ajv via:
Thank you.
Ajv generates code 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:
Performance of different validators by json-schema-benchmark:
addSchema
or compiled to be available)type
keywordsconst
, contains
, propertyNames
and if/then/else
true
/false
as a schema to always pass/fail).To install version 7:
npm install ajv@beta
To install the previous version 6:
npm install ajv
Try it in the Node.js REPL: https://runkit.com/npm/ajv
In JavaScript:
// or ESM/TypeScript import
import Ajv from "ajv"
// Node.js require:
const Ajv = require("ajv").default
const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}
const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) console.log(validate.errors)
In TypeScript:
import Ajv, {JSONSchemaType, DefinedError} from "ajv"
const ajv = new Ajv()
type MyData = {foo: number}
// optional schema type annotation for schema to match MyData type
const schema: JSONSchemaType<MyData> = {
type: "object",
properties: {
foo: {type: "number", minimum: 0},
},
required: ["foo"],
additionalProperties: false,
}
// validate is a type guard for MyData - type is inferred from schema type
const validate = ajv.compile(schema)
// or, if you did not use type annotation for the schema,
// type parameter can be used to make it type guard:
// const validate = ajv.compile<MyData>(schema)
const data: any = {foo: 1}
if (validate(data)) {
// data is MyData here
console.log(data.foo)
} else {
// The type cast is needed to allow user-defined keywords and errors
// You can extend this type to include your error types as needed.
for (const err of validate.errors as DefinedError[]) {
switch (err.keyword) {
case "minimum":
// err type is narrowed here to have "minimum" error params properties
console.log(err.params.limit)
break
// ...
}
}
}
See this test for an advanced example, API reference and Options for more details.
Ajv compiles schemas to functions and caches them in all cases (using schema itself as a key for Map) or another function passed via options), 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 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
See Content Security Policies to decide the best approach how to use Ajv in the browser.
Whether you use Ajv or compiled schemas, it is recommended that you bundle them together with your code.
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; it creates global Ajv
if no module system is found.
The browser bundle is available on cdnjs.
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).
CLI is available as a separate npm package ajv-cli. It supports:
Ajv can be extended with plugins that add keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions:
Youcan import Plugin
interface from ajv if you use Typescript.
If you have published a useful plugin please submit a PR to add it to the next section.
idn-hostname
, idn-email
, iri
, iri-reference
and duration
).npm install
git submodule update --init
npm test
npm run build
- compiles typescript to dist folder.
npm run watch
- automatically compiles typescript when files in lib folder change
Please see Contributing guidelines
See https://github.com/ajv-validator/ajv/releases
Please note: Changes in version 7.0.0-beta
Please review and follow the Code of conduct.
Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team.
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues.
Ajv is a part of Tidelift subscription - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers.
FAQs
Another JSON Schema Validator
The npm package ajv receives a total of 92,000,326 weekly downloads. As such, ajv popularity was classified as popular.
We found that ajv demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.