ajv-formats

repository·master·Indexed 42 days ago

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

A plugin for the Ajv v7+ JSON Schema validator that adds support for common string formats such as dates, URIs, emails, and IP addresses. It provides both full and fast validation modes and includes comparison keywords like formatMinimum and formatMaximum for orderable formats.

Tokens
2.5K
Snippets
9
Records
10
Agent score
54%

What's inside ajv-formats

  1. Use format comparison keywords like formatMinimum and formatMaximum

    master

    When ajv-formats is used without options or with { keywords: true }, it adds comparison keywords to your Ajv instance. These allow you to define minimum/maximum constraints for formats that support ordering (like date, time, and date-time).

    Supported Keywords

    • formatMinimum / formatMaximum
    • formatExclusiveMinimum / formatExclusiveMaximum

    These keywords apply only to strings. If the data is not a string, validation succeeds. The value for these keywords must be a string or a $data reference representing the allowed boundary.

    const Ajv = require("ajv")
    const addFormats = require("ajv-formats")
    
    const ajv = new Ajv()
    addFormats(ajv)
    
    const schema = {
      type: "string",
      format: "date",
      formatMinimum: "2016-02-06",
      formatExclusiveMaximum: "2016-12-27",
    }
    
    const validate = ajv.compile(schema)
    
    console.log(validate("2016-02-06")) // true
    console.log(validate("2016-12-26")) // true
    console.log(validate("2016-02-05")) // false
    console.log(validate("2016-12-27")) // false
    console.log(validate("abc"))        // true (not a string)
  2. Install and use ajv-formats with Ajv

    master

    To use JSON Schema formats with an Ajv instance, import addFormats and call it passing your Ajv instance as the first argument. This registers the standard set of formats with your validator.

    ESM/TypeScript

    import Ajv from "ajv"
    import addFormats from "ajv-formats"
    
    const ajv = new Ajv()
    addFormats(ajv)

    Node.js (CommonJS)

    const Ajv = require("ajv")
    const addFormats = require("ajv-formats")
    
    const ajv = new Ajv()
    addFormats(ajv)
    import Ajv from "ajv"
    import addFormats from "ajv-formats"
    
    const ajv = new Ajv()
    addFormats(ajv)
  3. Configure ajv-formats options

    master

    You can pass an options object as the second argument to addFormats(ajv, options) to control which formats are loaded and how they behave.

    1. Select specific formats

    Pass an array of format names to only add those specific formats to the Ajv instance.

    addFormats(ajv, ["date", "time"])

    2. Configure validation mode and keywords

    Use the mode and keywords options.

    • mode: Set to "fast" to use simplified regular expressions and skip range validation for certain formats (date, time, date-time, iso-time, iso-date-time, uri, uri-reference, email). This improves performance but reduces validation strictness.
    • keywords: Set to true to enable the comparison keywords (formatMinimum, etc.).

    Example: Fast mode with specific formats and keywords enabled

    addFormats(ajv, { mode: "fast", formats: ["date", "time"], keywords: true })
    addFormats(ajv, { mode: "fast", formats: ["date", "time"], keywords: true })
  4. Configure the formatsPlugin options

    master

    The formatsPlugin accepts two types of options: a simple array of format names or a FormatOptions object.

    FormatOptions

    • mode: Either "fast" or "full". "fast" uses a subset of formats optimized for performance, while "full" includes the complete set.
    • formats: An array of FormatName to specifically include.
    • keywords: A boolean (defaults to true). If true, it registers formatLimit keywords (like formatMaximum, formatMinimum, etc.) on the ajv instance.
    export interface FormatOptions {
      mode?: FormatMode
      formats?: FormatName[]
      keywords?: boolean
    }
    
    export type FormatsPluginOptions = FormatName[] | FormatOptions
  5. Reference the available formats in ajv-formats

    master

    The ajv-formats package provides the following format definitions for JSON Schema validation:

    • date: full-date (RFC3339)
    • time: time (time-zone is mandatory)
    • date-time: date-time (time-zone is mandatory)
    • iso-time: time with optional time-zone
    • iso-date-time: date-time with optional time-zone
    • duration: duration (RFC3339 appendix A)
    • uri: full URI
    • uri-reference: URI reference (full and relative)
    • uri-template: URI template (RFC6570)
    • url (deprecated): URL record
    • email: email address
    • hostname: host name (RFC1034)
    • ipv4: IP address v4
    • ipv6: IP address v6
    • regex: valid regular expression string
    • uuid: UUID (RFC4122)
    • json-pointer: JSON-pointer (RFC6901)
    • relative-json-pointer: relative JSON-pointer
    • byte: base64 encoded data (OpenAPI 3.0.0)
    • int32: signed 32-bit integer (OpenAPI 3.0.0)
    • int64: signed 64-bit integer (OpenAPI 3.0.0)
    • float: float (OpenAPI 3.0.0)
    • double: double (OpenAPI 3.0.0)
    • password: password string (OpenAPI 3.0.0)
    • binary: binary string (OpenAPI 3.0.0)

    Note: For international characters in URLs, hostnames, and emails (iri, iri-reference, idn-hostname, idn-email), use the ajv-formats-draft2019 plugin instead.

  6. Register formats with Ajv using the formatsPlugin

    master

    The formatsPlugin is the primary entrypoint for adding format validation to an Ajv instance. It can be used as a plugin by passing it to ajv.addFormat or by calling it directly with an Ajv instance.

    By default, it adds all available formats and enables formatLimit keywords. You can customize the plugin to only include specific formats, switch between fast and full modes, or disable the automatic addition of limit keywords.

    import Ajv from "ajv";
    import formatsPlugin from "ajv-formats";
    
    const ajv = new Ajv();
    
    // Basic usage: adds all formats and limit keywords
    formatsPlugin(ajv);
    
    // Usage with specific formats
    formatsPlugin(ajv, {
      formats: ["email", "date-time"],
      mode: "fast"
    });
  7. Use fastFormats for high-performance validation

    master

    The fastFormats object provides a subset of the full formats optimized for speed. It uses simpler regular expressions for formats like date, time, email, and uri. This is ideal for performance-critical applications where strict standard compliance (e.g., complex RFC edge cases) is less important than validation throughput.

    import { fastFormats } from 'ajv-formats';
    
    // fastFormats includes a subset of fullFormats with optimized regex:
    // date, time, date-time, iso-time, iso-date-time, uri, 
    // uri-reference, email
  8. Use fullFormats for comprehensive validation

    master

    The fullFormats object contains the complete set of format definitions provided by this package. Each definition includes a validator (often a RegExp or a function) and, where applicable, a comparison function for sorting or comparing values. Use this when you need strict adherence to standards like RFC 3339 for dates or RFC 6901 for JSON pointers.

    import { fullFormats } from 'ajv-formats';
    
    // fullFormats contains all supported formats including:
    // date, time, date-time, iso-time, iso-date-time, duration, uri, 
    // uri-reference, uri-template, url, email, hostname, ipv4, ipv6, 
    // regex, uuid, json-pointer, json-pointer-uri-fragment, 
    // relative-json-pointer, byte, int32, int64, float, double, 
    // password, binary
  9. Available JSON Schema format names

    master

    The ajv-formats package provides a set of predefined format names that can be used in JSON Schema validation. These names are used to identify specific data types and patterns like dates, URIs, emails, and more.

    // The following are valid FormatName values:
    // "date" | "time" | "date-time" | "iso-time" | "iso-date-time" | "duration" | "uri" | "uri-reference" | "uri-template" | "url" | "email" | "hostname" | "ipv4" | "ipv6" | "regex" | "uuid" | "json-pointer" | "json-pointer-uri-fragment" | "relative-json-pointer" | "byte" | "int32" | "int64" | "float" | "double" | "password" | "binary"
  10. Retrieve a specific format with formatsPlugin.get()

    master

    The formatsPlugin exports a get method that allows you to manually retrieve a specific Format definition from the plugin's internal registry. This is useful if you need to access the underlying validation logic outside of the standard Ajv registration flow.

    • format: FormatName: The name of the format to retrieve.
    • mode?: FormatMode: The mode to search in ("fast" or "full"). Defaults to "full".
    import formatsPlugin from "ajv-formats";
    
    // Retrieve the 'email' format in 'full' mode
    const emailFormat = formatsPlugin.get("email");
    
    // Retrieve a format in 'fast' mode
    const fastDate = formatsPlugin.get("date", "fast");