### Install Ajv.js (Latest Version) Source: https://ajv.js.org/guide/getting-started Installs the latest version of Ajv.js using npm. This is the recommended way to get started with Ajv for current JSON Schema drafts. ```bash npm install ajv ``` -------------------------------- ### Install Ajv.js (Version 6 for Draft-04) Source: https://ajv.js.org/guide/getting-started Installs Ajv.js version 6, which is required for compatibility with JSON Schema draft-04. Use this if you are working with older schemas. ```bash npm install ajv@6 ``` -------------------------------- ### Install Dependencies and Run Tests (Shell) Source: https://ajv.js.org/packages/ajv-formats.html Commands to install project dependencies, update git submodules, and run tests. ```shell npm install git submodule update --init npm test ``` -------------------------------- ### Install ajv-cli globally Source: https://ajv.js.org/packages/ajv-cli.html Installs the ajv-cli package globally using npm to enable command-line access. ```bash npm install -g ajv-cli ``` -------------------------------- ### Run Tests and Build Source: https://ajv.js.org/packages/ajv-i18n Commands to initialize submodules, install dependencies, run the test suite, and compile localization templates. ```bash npm install git submodule update --init npm test npm run build ``` -------------------------------- ### Install ajv-keywords Source: https://ajv.js.org/packages/ajv-keywords.html Installs the ajv-keywords package using npm. This command is used to add the library to your project's dependencies, typically for use with Ajv v7. ```bash npm install ajv-keywords ``` -------------------------------- ### Basic Data Validation with JSON Schema Source: https://ajv.js.org/guide/getting-started Demonstrates how to validate data against a JSON Schema using Ajv. It shows schema definition, compilation, and validation of a sample data object. Errors are logged if validation fails. ```javascript const Ajv = require("ajv") const ajv = new Ajv() // options can be passed, e.g. {allErrors: true} const schema = { type: "object", properties: { foo: {type: "integer"}, bar: {type: "string"} }, required: ["foo"], additionalProperties: false } const validate = ajv.compile(schema) const data = { foo: 1, bar: "abc" } const valid = validate(data) if (!valid) console.log(validate.errors) ``` -------------------------------- ### Initialize Ajv with Custom Options Source: https://ajv.js.org/options Demonstrates how to instantiate the Ajv validator with specific configuration options. In this example, the 'allErrors' flag is enabled to report all validation errors instead of stopping at the first failure. ```javascript const ajv = new Ajv({allErrors: true}) ``` -------------------------------- ### Install ajv-i18n via npm Source: https://ajv.js.org/packages/ajv-i18n The standard command to add the ajv-i18n package to your Node.js project dependencies. ```bash npm install ajv-i18n ``` -------------------------------- ### Ajv AnyOf Keyword Example Source: https://ajv.js.org/json-schema Demonstrates the 'anyOf' keyword in Ajv, allowing data to match one or more of the provided subschemas. This offers more flexibility than 'oneOf' and can be more performant. ```json { "type": "number", "anyOf": [ {"maximum": 3}, {"type": "integer"} ] } ``` -------------------------------- ### Create Ajv Instance Source: https://ajv.js.org/api.html Instantiates the Ajv validator. No specific options are provided in this basic example, meaning default options will be used. This is the entry point for using Ajv's validation capabilities. ```javascript const ajv = new Ajv() ``` -------------------------------- ### Basic Data Validation with JSON Type Definition (JTD) Source: https://ajv.js.org/guide/getting-started Illustrates data validation using JSON Type Definition (JTD) with Ajv. This example defines a schema with properties and optional properties, then compiles and validates sample data. ```javascript const Ajv = require("ajv/dist/jtd") const ajv = new Ajv() // options can be passed, e.g. {allErrors: true} const schema = { properties: { foo: {type: "int32"} }, optionalProperties: { bar: {type: "string"} } } const validate = ajv.compile(schema) const data = { foo: 1, bar: "abc" } const valid = validate(data) if (!valid) console.log(validate.errors) ``` -------------------------------- ### Configure Ajv with Custom Logger (JavaScript) Source: https://ajv.js.org/api.html Demonstrates how to initialize Ajv with a custom logger object. The logger must expose `log`, `warn`, and `error` methods. This example shows how to bind `console.log` and delegate to an `otherLogger` instance for `warn` and `error`. ```javascript const otherLogger = new OtherLogger() const ajv = new Ajv({ logger: { log: console.log.bind(console), warn: function warn() { otherLogger.logWarn.apply(otherLogger, arguments) }, error: function error() { otherLogger.logError.apply(otherLogger, arguments) console.error.apply(console, arguments) }, }, }) ``` -------------------------------- ### Reference Default Ajv Configuration Source: https://ajv.js.org/options Displays the default configuration object used by the Ajv constructor. Developers should only pass options that deviate from these defaults to maintain clean and efficient schema validation setups. ```typescript const defaultOptions = { strict: undefined, strictSchema: true, strictNumbers: true, strictTypes: "log", strictTuples: "log", strictRequired: false, allowUnionTypes: false, allowMatchingProperties: false, validateFormats: true, $data: false, allErrors: false, verbose: false, discriminator: false, unicodeRegExp: true, timestamp: undefined, parseDate: false, allowDate: false, int32range: true, $comment: false, formats: {}, keywords: {}, schemas: {}, logger: undefined, loadSchema: undefined, removeAdditional: false, useDefaults: false, coerceTypes: false, meta: true, validateSchema: true, addUsedSchema: true, inlineRefs: true, passContext: false, loopRequired: 200, loopEnum: 200, ownProperties: false, multipleOfPrecision: undefined, messages: true, uriResolver: undefined, code: { es5: false, esm: false, lines: false, source: false, process: undefined, optimize: true, regExp: RegExp } } ``` -------------------------------- ### Compile Combined Schemas using addSchema Method (JavaScript) Source: https://ajv.js.org/guide/combining-schemas.html This example shows an alternative method for compiling schemas with $ref by first creating an Ajv instance, then using the addSchema method to register the referenced schema ('defsSchema'), and finally compiling the main schema ('schema'). ```javascript const ajv = new Ajv() const validate = ajv.addSchema(defsSchema).compile(schema) ``` -------------------------------- ### Ajv OneOf Keyword Example Source: https://ajv.js.org/json-schema Illustrates the 'oneOf' keyword in Ajv, requiring data to match exactly one of the provided subschemas. This is useful for defining mutually exclusive data structures. ```json { "type": "number", "oneOf": [ {"maximum": 3}, {"type": "integer"} ] } ``` -------------------------------- ### $data Reference for Format Keyword (JavaScript) Source: https://ajv.js.org/guide/combining-schemas.html This JavaScript example utilizes the '$data' option to dynamically set the 'format' keyword based on the property name. The '$data: "0#"' reference points to the property name itself, ensuring the string value conforms to the format indicated by the field name (e.g., 'date-time', 'email'). ```javascript const schema = { additionalProperties: { type: "string", format: {$data: "0#"}, }, } const validData = { "date-time": "1963-06-19T08:30:06.283185Z", email: "joe.bloggs@example.com", } ``` -------------------------------- ### Initialize and Add Schemas to Ajv Instance (TypeScript) Source: https://ajv.js.org/guide/managing-schemas This snippet shows the TypeScript equivalent of initializing an Ajv instance and adding schemas. It utilizes ES module imports and type annotations for schemas, ensuring type safety. This setup is ideal for TypeScript projects aiming for centralized schema management. ```typescript import Ajv from "ajv" import * as schema_user from "./schema_user.json" import * as schema_document from "./schema_document.json" export const ajv = new Ajv() ajv.addSchema(schema_user, "user") ajv.addSchema(schema_document, "document") ``` -------------------------------- ### Addressing Contradictory Types in Ajv Source: https://ajv.js.org/strict-mode Shows how Ajv's `strictTypes` option flags contradictory type keywords within a schema, such as defining an object that is also an array. The example demonstrates how to resolve such contradictions using `anyOf` or by explicitly defining compatible types. ```json { "type": "object", "anyOf": [ { "type": "array" }, { "type": "object" } ] } ``` ```json { "type": ["array", "object"], "anyOf": [ { "type": "array" }, { "type": "object" } ] } ``` -------------------------------- ### JSON Schema with `anyOf` for Object Validation (JavaScript) Source: https://ajv.js.org/strict-mode This example demonstrates using the `anyOf` keyword in JSON Schema to validate an object that must satisfy one of several subschemas. It illustrates that the 'type: "object"' keyword does not need to be repeated for each subschema if it's present in a parent schema, simplifying the schema definition. ```json { type: "object", anyOf: [ { properties: {foo: {type: "number"}} required: ["foo"] }, { properties: {bar: {type: "string"}} required: ["bar"] } ] } ``` -------------------------------- ### Compile JTD Parsers and Serializers with Ajv Source: https://ajv.js.org/guide/getting-started This snippet demonstrates how to use Ajv to compile both a serializer and a parser from a JTD schema. The serializer converts JavaScript objects to JSON strings, while the parser converts JSON strings to JavaScript objects. It highlights the performance benefits and error handling mechanisms provided by Ajv's compiled functions. ```javascript const Ajv = require("ajv/dist/jtd") const ajv = new Ajv() // options can be passed, e.g. {allErrors: true} const schema = { properties: { foo: {type: "int32"} }, optionalProperties: { bar: {type: "string"} } } const serialize = ajv.compileSerializer(schema) const data = { foo: 1, bar: "abc" } console.log(serialize(data)) const parse = ajv.compileParser(schema) const json = '{"foo": 1, "bar": "abc"}' const invalidJson = '{"unknown": "abc"}' parseAndLog(json) // logs {foo: 1, bar: "abc"} parseAndLog(invalidJson) // logs error and position function parseAndLog(json) { const data = parse(json) if (data === undefined) { console.log(parse.message) // error message from the last parse call console.log(parse.position) // error position in string } else { console.log(data) } } ``` -------------------------------- ### POST /Ajv/constructor Source: https://ajv.js.org/options Initializes a new Ajv instance with specific configuration options to control schema validation behavior. ```APIDOC ## POST /Ajv/constructor ### Description Initializes the Ajv validator instance. Options passed here determine how schemas are compiled and validated. ### Method POST (Constructor Initialization) ### Parameters #### Request Body - **allErrors** (boolean) - Optional - If true, returns all validation errors instead of failing on the first one. - **strict** (boolean|string) - Optional - Configures strict mode (true, "log", or false). - **strictSchema** (boolean|string) - Optional - Prevents unknown keywords or formats. - **strictNumbers** (boolean) - Optional - If true, fails validation on NaN or Infinity. - **useDefaults** (boolean) - Optional - If true, modifies data by applying default values defined in the schema. - **coerceTypes** (boolean) - Optional - If true, attempts to coerce data types to match the schema. ### Request Example { "allErrors": true, "strict": "log", "useDefaults": true } ### Response #### Success Response (200) - **ajvInstance** (object) - The configured Ajv validator instance. #### Response Example { "status": "success", "message": "Ajv instance initialized" } ``` -------------------------------- ### Initialize ajv-formats with Ajv Source: https://ajv.js.org/packages/ajv-formats.html Demonstrates how to import and register the ajv-formats plugin with an Ajv instance using both ESM/TypeScript and Node.js require syntax. ```javascript // ESM/TypeScript import import Ajv from "ajv" import addFormats from "ajv-formats" // Node.js require: const Ajv = require("ajv") const addFormats = require("ajv-formats") const ajv = new Ajv() addFormats(ajv) ``` -------------------------------- ### typeof keyword validation examples Source: https://ajv.js.org/packages/ajv-keywords.html Provides examples of using the 'typeof' keyword for JSON-Schema validation. It checks if the data's type matches the specified string or an array of strings. ```javascript ajv.validate({typeof: "undefined"}, undefined) // true ajv.validate({typeof: "undefined"}, null) // false ajv.validate({typeof: ["undefined", "object"]}, null) // true ``` -------------------------------- ### Access ajv-cli help commands Source: https://ajv.js.org/packages/ajv-cli.html Displays help information for various ajv-cli commands to understand usage and parameters. ```bash ajv help ajv help validate ajv help compile ajv help migrate ajv help test ``` -------------------------------- ### Install ajv-errors using npm Source: https://ajv.js.org/packages/ajv-errors.html This snippet shows the command to install the ajv-errors package using npm. This is the first step to integrate custom error messages into your Ajv validator. ```bash npm install ajv-errors ``` -------------------------------- ### Constructor: new Ajv() Source: https://ajv.js.org/api.html Initializes a new instance of the Ajv validator. ```APIDOC ## Constructor: new Ajv() ### Description Creates a new Ajv instance for schema compilation and validation. ### Request Example ```javascript const ajv = new Ajv() ``` ``` -------------------------------- ### Method Chaining with Ajv Source: https://ajv.js.org/api.html Demonstrates how Ajv methods prefixed with 'add' or 'remove' return the instance to allow for fluent method chaining. ```javascript const validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); ``` -------------------------------- ### Ajv Not Keyword Example Source: https://ajv.js.org/json-schema Explains the 'not' keyword in Ajv, which negates a subschema. Data is considered valid if it does not match the schema provided within the 'not' keyword. ```json { "type": "number", "not": {"minimum": 3} } ``` -------------------------------- ### Add ajv-formats Plugin (TypeScript) Source: https://ajv.js.org/guide/formats Initializes Ajv and adds all formats provided by the ajv-formats plugin using TypeScript syntax. This mirrors the JavaScript setup for format validation. ```typescript import Ajv from "ajv" import addFormats from "ajv-formats" const ajv = new Ajv() addFormats(ajv) ``` -------------------------------- ### Usage: Add all keywords via Ajv options Source: https://ajv.js.org/packages/ajv-keywords.html Demonstrates initializing Ajv with all custom keywords defined in ajv-keywords through the 'keywords' option. This approach integrates keywords during Ajv instantiation. ```javascript const ajv = new Ajv({keywords: require("ajv-keywords/dist/definitions")(opts)}) ``` -------------------------------- ### Add ajv-formats Plugin (JavaScript) Source: https://ajv.js.org/guide/formats Initializes Ajv and adds all formats provided by the ajv-formats plugin. This is a common setup for enabling standard JSON Schema format validation. ```javascript const Ajv = require("ajv") const addFormats = require("ajv-formats") const ajv = new Ajv() addFormats(ajv) ``` -------------------------------- ### Ajv Const Keyword Example Source: https://ajv.js.org/json-schema Shows the 'const' keyword in Ajv, which validates that the data is deeply equal to a specific value. This is useful for fixed values and can be combined with $data references. ```json { "const": "foo" } ``` -------------------------------- ### Usage: Add all keywords to Ajv Source: https://ajv.js.org/packages/ajv-keywords.html Demonstrates how to add all available custom keywords to an Ajv instance. It requires importing Ajv and ajv-keywords, then initializing Ajv and applying the keywords. ```javascript const Ajv = require("ajv") const ajv = new Ajv() require("ajv-keywords")(ajv) ajv.validate({instanceof: "RegExp"}, /.*/) // true ajv.validate({instanceof: "RegExp"}, ".*") // false ``` -------------------------------- ### Define strict tuple validation using prefixItems Source: https://ajv.js.org/json-schema Shows how to use 'prefixItems' to validate specific array indices. This example defines a schema that expects an integer followed by a string. ```json { "type": "array", "prefixItems": [{ "type": "integer" }, { "type": "string" }] } ``` -------------------------------- ### Ajv Enum Keyword Example Source: https://ajv.js.org/json-schema Illustrates the 'enum' keyword in Ajv, which validates data against a list of possible values. The data must be deeply equal to one of the items in the provided array. ```json { "enum": [ 2, "foo", { "foo": "bar" }, [ 1, 2, 3 ] ] } ``` -------------------------------- ### Initialize AJV with $merge and $patch Keywords (JavaScript) Source: https://ajv.js.org/guide/combining-schemas.html This code snippet demonstrates how to add the $merge and $patch keywords to an AJV instance using the ajv-merge-patch package. It requires the package and then calls a function to extend the AJV instance. ```javascript require("ajv-merge-patch")(ajv) ``` -------------------------------- ### instanceof keyword validation examples Source: https://ajv.js.org/packages/ajv-keywords.html Illustrates the use of the 'instanceof' keyword for validating JavaScript object types. It checks if an instance belongs to a specified constructor or an array of constructors. ```javascript ajv.validate({instanceof: "Array"}, []) // true ajv.validate({instanceof: "Array"}, {}) // false ajv.validate({instanceof: ["Array", "Function"]}, function () {}) // true ``` -------------------------------- ### Configure Transpilers for Asynchronous Validation Source: https://ajv.js.org/guide/async-validation.html Shows how to initialize Ajv with a custom transpiler function using the 'processCode' option to support older environments or specific async function requirements. ```javascript const ajv = new Ajv({processCode: transpileFunc}) const validate = ajv.compile(schema) validate(data).then(successFunc).catch(errorFunc) ``` -------------------------------- ### Apply format comparison keywords Source: https://ajv.js.org/packages/ajv-formats.html Shows how to use formatMinimum and formatExclusiveMaximum keywords to constrain date-formatted strings. These keywords require the format to be defined and support date, time, and date-time types. ```javascript require("ajv-formats")(ajv) const schema = { type: "string", format: "date", formatMinimum: "2016-02-06", formatExclusiveMaximum: "2016-12-27", } const validDataList = ["2016-02-06", "2016-12-26"] const invalidDataList = ["2016-02-05", "2016-12-27", "abc"] ``` -------------------------------- ### Initialize Ajv for JSON Schema Draft-04 (TypeScript) Source: https://ajv.js.org/json-schema Initializes an Ajv instance for JSON Schema draft-04 using ES module imports and the `ajv-draft-04` package. This setup is isolated to draft-04 validation. ```typescript import Ajv from "ajv-draft-04" const ajv = new Ajv() ``` -------------------------------- ### Define JTD Reference and Recursive Schemas Source: https://ajv.js.org/json-type-definition Shows how to handle complex schemas using definitions. The first example demonstrates a simple reference, while the second shows a recursive LinkedList structure. ```typescript const schema: JTDSchemaType<{val: number}, {num: number}> = { definitions: { num: {type: "float64"}, }, properties: { val: {ref: "num"}, }, } type LinkedList = {val: number; next?: LinkedList} const schema: JTDSchemaType = { definitions: { node: { properties: { val: {type: "float64"}, }, optionalProperties: { next: {ref: "node"}, }, }, }, ref: "node", } ``` -------------------------------- ### Browser Script Loading for Ajv7 (JSON Schema draft-07) Source: https://ajv.js.org/guide/environments.html Demonstrates how to include and initialize Ajv version 7 for JSON Schema draft-07 in a browser environment using a UMD bundle. It assumes the ajv7.min.js script is loaded, making the Ajv constructor available globally. ```html ``` -------------------------------- ### Implement Localization in Node.js Source: https://ajv.js.org/packages/ajv-i18n Demonstrates how to import the library, validate data using Ajv, and apply a specific locale to the validation errors. The output can then be formatted using ajv.errorsText. ```javascript const Ajv = require("ajv") // version >= 8.0.0 const localize = require("ajv-i18n") const ajv = Ajv({allErrors: true, messages: false}) const validate = ajv.compile(schema) const valid = validate(data) if (!valid) { localize.ru(validate.errors) console.log(ajv.errorsText(validate.errors, {separator: '\n'})) } ``` -------------------------------- ### Import Specific Locales Source: https://ajv.js.org/packages/ajv-i18n Shows how to import individual locale files to reduce bundle size, which is useful for environments like browserify or when only specific languages are required. ```javascript const localize_ru = require('ajv-i18n/localize/ru') const localize = { en: require('ajv-i18n/localize/en'), ru: require('ajv-i18n/localize/ru'), } ``` -------------------------------- ### Ajv Custom 'range' Keyword Example Source: https://ajv.js.org/keywords.html Illustrates the definition of a custom 'range' keyword for validating numbers within a specified minimum and maximum. It supports an 'exclusiveRange' option in the parent schema to control inclusivity. ```typescript import {_, nil, KeywordCxt} from Ajv ajv.addKeyword({ keyword: "range", type: "number", code(cxt: KeywordCxt) { const {schema, parentSchema, data} = cxt const [min, max] = schema const eq: Code = parentSchema.exclusiveRange ? _`=` : nil cxt.fail(_`${data} <${eq} ${min} || ${data} >${eq} ${max}`) }, metaSchema: { type: "array", items: [{type: "number"}, {type: "number"}], minItems: 2, additionalItems: false, }, }) ``` -------------------------------- ### Equivalent JSON Schema after $merge or $patch Source: https://ajv.js.org/guide/combining-schemas.html This JSON schema represents the equivalent structure after applying either the $merge or $patch operations shown in previous examples. It consolidates properties from the source and merged/patched schemas. ```json { "type": "object", "properties": { "p": {"type": "string"}, "q": {"type": "number"} }, "additionalProperties": false } ``` -------------------------------- ### Browser Script Loading for Ajv2019 (JSON Schema draft-2019-09) Source: https://ajv.js.org/guide/environments.html Illustrates loading and initializing Ajv for JSON Schema draft-2019-09 in a browser using a UMD bundle. The ajv2019.min.js script makes the Ajv constructor globally accessible as `window.ajv2019`. ```html ``` -------------------------------- ### Configure Allowed Keywords and Vocabularies in Ajv Source: https://ajv.js.org/strict-mode Demonstrates how to explicitly permit unknown keywords or vocabularies that would otherwise trigger strict mode errors during schema compilation. ```javascript ajv.addKeyword("allowedKeyword"); ajv.addVocabulary(["allowed1", "allowed2"]); ``` -------------------------------- ### Ajv Custom 'even' Keyword Example Source: https://ajv.js.org/keywords.html Demonstrates how to define and add a custom 'even' keyword to Ajv using code generation. This keyword checks if a number is even, accepting a boolean schema value to control the check. ```typescript import {_, KeywordCxt} from Ajv ajv.addKeyword({ keyword: "even", type: "number", schemaType: "boolean", // $data: true // to support [$data reference](./guide/combining-schemas.md#data-reference), ... code(cxt: KeywordCxt) { const {data, schema} = cxt const op = schema ? _`!==` : _`===` cxt.fail(_`${data} %2 ${op} 0`) // ... the only code change needed is to use `cxt.fail$data` here }, }) const schema = {even: true} const validate = ajv.compile(schema) console.log(validate(2)) // true console.log(validate(3)) // false ``` -------------------------------- ### JSON Schema using $patch Keyword Source: https://ajv.js.org/guide/combining-schemas.html An example of a JSON Schema using the $patch keyword. The `$patch` keyword applies changes to a `source` schema using operations defined in the `with` property, which is an array of JSON Patch operations. ```json { "$patch": { "source": { "type": "object", "properties": {"p": {"type": "string"}}, "additionalProperties": false }, "with": [{"op": "add", "path": "/properties/q", "value": {"type": "number"}}] } } ``` -------------------------------- ### Browser Script Loading for AjvJTD (JSON Type Definition) Source: https://ajv.js.org/guide/environments.html Shows how to load and instantiate Ajv for JSON Type Definition (JTD) in a web browser using its UMD bundle. The ajvJTD.min.js file exposes the JTD constructor globally as `window.ajvJTD`. ```html ``` -------------------------------- ### Validate data using generated CJS/ESM modules Source: https://ajv.js.org/standalone Demonstrates how to import and execute generated validation functions to check data against schemas. Examples cover single schema validation in CJS and multiple schema validation in both CJS and ESM. ```javascript // CJS Single Schema const Bar = require('./validate-cjs') const barFail = {} if (!Bar(barFail)) console.log(Bar.errors) // CJS Multiple Schemas const validations = require('./validate-cjs') let validateFoo = validations["#/definitions/Foo"]; if (!validateFoo({})) console.log(validateFoo.errors); // ESM Multiple Schemas import {Foo} from './validate-multiple-esm.mjs'; if (!Foo({})) console.log(Foo.errors); ``` -------------------------------- ### Compile Combined Schemas by Passing All to Ajv Instance (JavaScript) Source: https://ajv.js.org/guide/combining-schemas.html This code illustrates how to compile schemas that reference each other by passing an array of all schema objects to the Ajv constructor. It then retrieves a compiled validation function using the schema's $id. ```javascript const ajv = new Ajv({schemas: [schema, defsSchema]}) const validate = ajv.getSchema("http://example.com/schemas/schema.json") ``` -------------------------------- ### Define custom error messages for required properties in JavaScript Source: https://ajv.js.org/packages/ajv-errors.html This example demonstrates how to specify custom error messages for individual required properties within a JSON schema. This provides more context-specific feedback when required fields are missing. ```javascript const schema = { type: "object", required: ["foo", "bar"], properties: { foo: {type: "integer"}, bar: {type: "string"}, }, errorMessage: { type: "should be an object", // will not replace internal "type" error for the property "foo" required: { foo: 'should have an integer property "foo"', bar: 'should have a string property "bar"', }, }, } ``` -------------------------------- ### Define dynamic defaults with parameters Source: https://ajv.js.org/packages/ajv-keywords.html Demonstrates how to create dynamic default functions that accept arguments, enabling configurable behavior like choosing a specific UUID version. ```javascript function getUuid(args) { const version = "v" + ((args && args.v) || "4") return uuid[version] } const def = require("ajv-keywords/dist/definitions/dynamicDefaults") def.DEFAULTS.uuid = getUuid const schema = { dynamicDefaults: { id1: "uuid", id2: {func: "uuid", v: 4}, id3: {func: "uuid", v: 1}, }, } ```