Popularity
8.4
Growing
Activity
9.4
-
8,286
102
616

Code Quality Rank: L4
Monthly Downloads: 0
Programming language: JavaScript
License: MIT License
Latest version: v7.0.0-beta.7

ajv alternatives and similar modules

Based on the "Data Validation" category

Do you think we are missing an alternative of ajv or a related project?

Add another 'Data Validation' Module

README

Ajv: Another JSON Schema Validator

The fastest JSON Schema validator for Node.js and browser. Supports draft-06/07/2019-09 (draft-04 is supported in version 6).

Build Status npm npm (beta) npm downloads Coverage Status Gitter GitHub Sponsors

Platinum sponsors

Using version 7 (beta)

Ajv version 7 (beta) is released with these changes:

  • support of JSON Schema draft-2019-09 features: [unevaluatedProperties](./json-schema.md#unevaluatedproperties) and [unevaluatedItems](./json-schema.md#unevaluateditems), [dynamic recursive references](./validation.md#extending-recursive-schemas) and other [additional keywords](./json-schema.md#json-schema-draft-2019-09).
  • to reduce the mistakes in JSON schemas and unexpected validation results, [strict mode](./docs/strict-mode.md) is added - it prohibits ignored or ambiguous JSON Schema elements.
  • to make code injection from untrusted schemas impossible, [code generation](./docs/codegen.md) is fully re-written to be safe and to allow code optimization (compiled schema code size is reduced by more than 10%).
  • to simplify Ajv extensions, the new keyword API that is used by pre-defined keywords is available to user-defined keywords - it is much easier to define any keywords now, especially with subschemas. ajv-keywords package was updated to use the new API (in v4.0.0-beta.0)
  • schemas are compiled to ES6 code (ES5 code generation is also supported with an option).
  • to improve reliability and maintainability the code is migrated to TypeScript.

Please note:

  • the support for JSON-Schema draft-04 is removed - if you have schemas using "id" attributes you have to replace them with "\$id" (or continue using Ajv v6 that will be supported until 02/28/2021).
  • all formats are separated to ajv-formats package - they have to be explicitly added if you use them.

See release notes for the details.

To install the new version:

npm install ajv@beta

See Getting started for code example.

Contents

  • Mozilla MOSS grant and OpenJS Foundation
  • Sponsors
  • Performance
  • Features
  • Getting started
  • [Frequently Asked Questions](./docs/faq.md)
  • Using in browser
    • [Content Security Policies](./docs/security.md#content-security-policies)
  • Command line interface
  • [API reference](./docs/api.md)
    • [Methods](./docs/api.md#ajv-constructor-and-methods)
    • [Options](./docs/api.md#options)
    • [Validation errors](./docs/api.md#validation-errors)
  • NEW: [Strict mode](./docs/strict-mode.md#strict-mode)
    • [Prohibit ignored keywords](./docs/strict-mode.md#prohibit-ignored-keywords)
    • [Prevent unexpected validation](./docs/strict-mode.md#prevent-unexpected-validation)
    • [Strict types](./docs/strict-mode.md#strict-types)
    • [Strict number validation](./docs/strict-mode.md#strict-number-validation)
  • [Data validation](./docs/validation.md)
    • [Validation basics](./docs/validation.md#validation-basics): [JSON Schema keywords](./docs/validation.md#validation-keywords), [annotations](./docs/validation.md#annotation-keywords), [formats](./docs/validation.md#formats)
    • [Modular schemas](./docs/validation.md#modular-schemas): [combining with \$ref](./docs/validation.md#ref), [\$data reference](./docs/validation.md#data-reference), [$merge and $patch](./docs/validation.md#merge-and-patch-keywords)
    • [Asynchronous schema compilation](./docs/validation.md#asynchronous-schema-compilation)
    • [Asynchronous validation](./docs/validation.md#asynchronous-validation)
    • [Modifying data](./docs/validation.md#modifying-data-during-validation): [additional properties](./docs/validation.md#removing-additional-properties), [defaults](./docs/validation.md#assigning-defaults), [type coercion](./docs/validation.md#coercing-data-types)
  • [User-defined keywords](./docs/keywords.md)
  • [Security considerations](./docs/security.md)
    • [Security contact](./docs/security.md#security-contact)
    • [Untrusted schemas](./docs/security.md#untrusted-schemas)
    • [Circular references in objects](./docs/security.md#circular-references-in-javascript-objects)
    • [Trusted schemas](./docs/security.md#security-risks-of-trusted-schemas)
    • [ReDoS attack](./docs/security.md#redos-attack)
    • [Content Security Policies](./docs/security.md#content-security-policies)
  • Plugins
  • Related packages
  • Some packages using Ajv
  • Tests, Contributing, Changes history
  • Support, Code of conduct, Contacts, License

Mozilla MOSS grant and OpenJS Foundation

   

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 (RFC8927).

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.

Please sponsor Ajv development

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.

Open Collective sponsors

Performance

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:

performance

Features

  • Ajv implements full JSON Schema draft-06/07 standards (draft-04 is supported in v6):
    • all validation keywords (see [JSON Schema validation keywords](./docs/json-schema.md))
    • keyword "nullable" from Open API 3 specification.
    • full support of remote references (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
    • formats defined by JSON Schema draft-07 standard (with ajv-formats plugin) and additional formats (can be turned off)
    • [validates schemas against meta-schema](./docs/api.md#api-validateschema)
  • supports browsers and Node.js 0.10-14.x
  • [asynchronous loading](./docs/validation.md#asynchronous-schema-compilation) of referenced schemas during compilation
  • "All errors" validation mode with [option allErrors](./docs/api.md#options)
  • [error messages with parameters](./docs/api.md#validation-errors) describing error reasons to allow error message generation
  • i18n error messages support with ajv-i18n package
  • [removing-additional-properties](./docs/validation.md#removing-additional-properties)
  • [assigning defaults](./docs/validation.md#assigning-defaults) to missing properties and items
  • [coercing data](./docs/validation.md#coercing-data-types) to the types specified in type keywords
  • user-defined keywords
  • draft-06/07 keywords const, contains, propertyNames and if/then/else
  • draft-06 boolean schemas (true/false as a schema to always pass/fail).
  • additional extension keywords with ajv-keywords package
  • [\$data reference](./docs/validation.md#data-reference) to use values from the validated data as values for the schema keywords
  • [asynchronous validation](./docs/api.md#asynchronous-validation) of user-defined formats and keywords

Install

To install version 7:

npm install ajv@beta

To install the previous version 6:

npm install ajv

Getting started

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](./spec/types/json-schema.spec.ts) for an advanced example, [API reference](./docs/api.md) and [Options](./docs/api.md#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](./docs/api.md#validation-errors)

Using in browser

See [Content Security Policies](./docs/security.md#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).

Command line interface

CLI is available as a separate npm package ajv-cli. It supports:

  • compiling JSON Schemas to test their validity
  • BETA: generating standalone module exporting a validation function to be used without Ajv (using ajv-pack)
  • migrate schemas to draft-07 (using json-schema-migrate)
  • validating data file(s) against JSON Schema
  • testing expected validity of data against JSON Schema
  • referenced schemas
  • user-defined meta-schemas
  • files in JSON, JSON5, YAML, and JavaScript format
  • all Ajv options
  • reporting changes in data after validation in JSON-patch format

Plugins

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:

  • it exports a function
  • this function accepts ajv instance as the first parameter and returns the same instance to allow chaining
  • this function can accept an optional configuration as the second parameter

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.

  • ajv-bsontype - plugin to validate mongodb's bsonType formats
  • ajv-cli - command line interface
  • ajv-formats - formats defined in JSON Schema specification.
  • ajv-errors - plugin for defining error messages in the schema
  • ajv-i18n - internationalised error messages
  • ajv-istanbul - plugin to instrument generated validation code to measure test coverage of your schemas
  • ajv-keywords - plugin with additional validation keywords (select, typeof, etc.)
  • ajv-merge-patch - plugin with keywords $merge and $patch
  • ajv-pack - produces a compact module exporting validation functions
  • ajv-formats-draft2019 - format validators for draft2019 that aren't included in ajv-formats (ie. idn-hostname, idn-email, iri, iri-reference and duration).

Some packages using Ajv

Tests

npm install
git submodule update --init
npm test

Contributing

npm run build - compiles typescript to dist folder.

npm run watch - automatically compiles typescript when files in lib folder change

Please see [Contributing guidelines](./CONTRIBUTING.md)

Changes history

See https://github.com/ajv-validator/ajv/releases

Please note: Changes in version 7.0.0-beta

Version 6.0.0.

Code of conduct

Please review and follow the [Code of conduct](./CODE_OF_CONDUCT.md).

Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team.

Security contact

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.

Open-source software support

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.

License

[MIT](./LICENSE)


*Note that all licence references and agreements mentioned in the ajv README section above are relevant to that project's source code only.