ajv
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
fast-deep-equal | 3.1.3 | 3.57 kB | MIT | prod | |
json-schema-traverse | 1.0.0 | 5.93 kB | MIT | prod | |
require-from-string | 2.0.2 | 1.77 kB | MIT | prod | |
uri-js | 4.4.1 | 128.91 kB | BSD-2-Clause | prod |
Ajv, short for Another JSON Schema Validator, is a powerful JSON validator for Node.js and browsers. It is acknowledged as one of the fastest JSON validators as it converts JSON Schemas into super-fast validation functions optimized for v8 JavaScript engine. Ajv supports all validation keywords of JSON Schema draft-04/06/07/2019-09/2020-12, provides full support of remote references, ensures correct string lengths for unicode pairs, allows asynchronous loading of referenced schemas and many more advanced features. Notably, it also offers Ajv i18n package for internationalized error messages.
To use Ajv, first ensure you have it installed in your project by running npm install ajv
in your command line terminal. Once installed, import the Ajv module and create an instance of it. You can then use compile
method to create a validation function from your JSON schema. After the validation function is generated, you can validate your data using this function. Example usage in JavaScript is as follows:
import Ajv from "ajv";
const ajv = new Ajv();
const schema = {
type: "object",
properties: {
foo: {type: "integer"},
bar: {type: "string"},
},
required: ["foo"],
additionalProperties: false,
};
const data = {
foo: 1,
bar: "abc",
};
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) console.log(validate.errors);
In this example, a data object is tested against the defined schema. The valid
constant returns true if data is valid against the schema or false otherwise. If data is invalid, the validation errors can be obtained from validate.errors
.
All documentation needed to utilize Ajv to its full potential can be found on the Ajv website. Useful links on the website include the "Getting started" guide, API reference, FAQ, and more advanced topics like security considerations, standalone validation code, strict mode, and JSON Schema vs JSON Type Definition comparison.