Ajv JSON Schema Validator

repository·master·Indexed 12 days ago

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

A high-performance JSON schema validator for Node.js and browser environments. Ajv supports multiple JSON Schema drafts (06, 07, 2019-09, 2020-12) and the JSON Type Definition (JTD) standard (RFC8927). It compiles schemas into optimized JavaScript code for efficient validation and provides features such as custom keywords, formats, asynchronous validation, and JTD parsing and serialization.

Tokens
46.3K
Snippets
143
Records
197
Agent score
96%

What's inside Ajv

  1. Overview of Ajv JSON Schema Validator

    master

    Ajv is a high-performance JSON validator for Node.js and the browser. It works by generating optimized code that turns JSON Schemas into highly efficient validation functions, making it suitable for performance-critical applications.

    Supported Schema Standards

    • JSON Schema Drafts: Supports draft-06, draft-07, 2019-09, and 2020-12.
      • Note: Support for draft-04 requires the separate ajv-draft-04 package.
    • JSON Type Definition (JTD): Supports RFC8927 including all JTD keywords, meta-schemas, and the union keyword.
    • OpenAPI Extensions: Includes support for discriminator and nullable keywords.

    Key Features

    • Remote & Recursive References: Full support for remote schemas (via addSchema) and recursive references between schemas.
    • Data Modification: Supports removing additional properties, assigning defaults to missing properties, and coercing data types to match schema specifications.
    • Validation Modes: Supports "All errors" mode via the allErrors option and asynchronous validation for user-defined formats and keywords.
    • Extensibility: Supports user-defined keywords, $data references, and additional extension keywords via the ajv-keywords package.
    • Error Handling: Provides parameterized error messages for custom error generation and supports i18n via the ajv-i18n package.
  2. Overview of Ajv features

    master

    Ajv is a high-performance JSON schema validator used in Node.js, browsers, Electron, and other JavaScript environments. Key features include:

    • Write less code: Implement complex validation logic via declarative schemas instead of manual code.
    • Super fast & secure: Compiles schemas into optimized JavaScript code for high performance.
    • Multi-standard: Supports both JSON Schema (various drafts) and JSON Type Definition (JTD).
  3. New features in Ajv v7

    master

    Ajv v7 introduced several significant improvements:

    • JSON Schema draft-2019-09 support: Includes keywords like unevaluatedProperties, unevaluatedItems, and dynamic recursive references.
    • Strict Mode: A new mode that prohibits ignored or ambiguous JSON Schema elements to reduce mistakes and unexpected validation results.
    • Improved Code Generation: Re-written to be safer against code injection from untrusted schemas and optimized to reduce compiled schema code size by over 10%.
    • ES6 Compilation: Schemas are compiled to ES6 code by default, though ES5 support is available via an option.
    • New Keyword API: A simplified API for defining user-defined keywords, making it easier to work with subschemas. The ajv-keywords package (v4.0.0+) uses this new API.
  4. Why use Ajv for data validation

    master

    Ajv is a high-performance JSON schema validator that allows you to replace manual validation and sanitization logic with declarative specifications.

    Key benefits include:

    • Reduced Codebase: Use concise JSON Schema or JSON Type Definition (JTD) instead of writing lengthy imperative validation code.
    • TypeScript Integration: Validation functions can be used as type guards, providing type-level guarantees that validated data matches your expected interfaces.
    • High Performance: Ajv compiles schemas into optimized JavaScript code designed for V8 engine optimization, making it significantly faster than many other validators.
    • Security: Since version 7, Ajv has been rebuilt with secure code generation as a primary objective, providing protections against remote code execution even when using untrusted schemas.
    • Multi-standard Support: Supports multiple JSON Schema drafts (including the latest draft 2020-12) and JSON Type Definition (RFC8927).
  5. New features in Ajv version 8

    master

    Ajv version 8 introduced several key improvements and support for newer standards:

    • JSON Schema draft-2020-12 support: Includes the prefixItems keyword, updated semantics for the items keyword, and support for dynamic recursive references.
    • OpenAPI support: Support for the discriminator keyword.
    • Improved JSON Type Definition (JTD) support:
      • Errors are now consistent with the JTD specification.
      • Error objects include additional properties to simplify error handling.
      • Internationalized error messages are available via the ajv-i18n package.
    • TypeScript enhancements: Support for type unions in the JSONSchemaType type.
  6. What is standalone validation code?

    master

    Standalone validation allows you to generate validation functions from JSON Schemas at compile/build time. These functions can be used at runtime without initializing the full Ajv instance.

    Benefits:

    • Reduced bundle size: Ajv itself does not need to be included in the client-side bundle.
    • Faster startup: Schema compilation happens during the build process rather than at runtime.
    • CSP Compatibility: Avoids the use of the Function constructor, which is often prohibited by strict Content Security Policies (CSP).
  7. JTD Type Form (Primitive Values)

    master

    The Type form defines a single primitive value. It requires a type member and supports optional nullable and metadata members.

    Supported type values:

    • "string"
    • "boolean"
    • "timestamp" (accepts RFC3339 strings or Date objects; configurable via the timestamp Ajv option)
    • Integers: "int8", "uint8", "int16", "uint16", "int32", "uint32"
    • Floats: "float32", "float64"

    Note: Unlike JSON Schema, JTD does not support multi-type definitions (e.g., string | number); use nullable: true if a value can be null.

    {
      type: "string"
    }
  8. Choose the appropriate Ajv class for your schema version

    master

    Ajv provides several specialized classes depending on the JSON Schema specification or format you are using. All classes inherit from the core Ajv class, which contains the methods for managing schemas and extensions.

    • Ajv (core): The base class without any pre-defined keywords. Use this if you want to build a custom validator from scratch.
    • Ajv (subclass from lib/ajv.ts): Includes JSON Schema draft-07 keywords. This is a common choice for standard JSON Schema validation.
    • Ajv (subclass from lib/2019.ts): Includes JSON Schema draft-2019-09 keywords.
    • Ajv (subclass from lib/jtd.ts): Includes support for JSON Type Definition (JTD).
  9. JTD Ref Form (Reference Definitions)

    master

    The Ref form allows you to reference a schema defined in the root definitions member of the schema. This is used to avoid duplication and enable recursion.

    Key Members:

    • ref: The name of the key in the definitions object.
    • nullable and metadata: Optional.

    Constraints:

    • You can only reference schemas located in the root-level definitions member.
    • You cannot reference the root of the schema directly (use a named definition instead).
    • You cannot reference schemas in other files (though you can combine files using JavaScript).
    {
      properties: {
        propFoo: {ref: "foo", nullable: true}
      },
      definitions: {
        foo: {type: "string"}
      }
    }