### Development Setup and Testing Source: https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md Commands to set up the development environment, install dependencies, and run tests. Ensure you have the latest stable Node.js and npm. ```bash npm install git submodule update --init npm test ``` -------------------------------- ### Add All Formats from ajv-formats (JavaScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/formats.md Installs all formats provided by the ajv-formats plugin. Ensure ajv-formats is installed as a dependency. ```javascript const Ajv = require("ajv") const addFormats = require("ajv-formats") const ajv = new Ajv() addFormats(ajv) ``` -------------------------------- ### Install Ajv v8 Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/getting-started.md Install the latest version of Ajv using npm. ```bash npm install ajv ``` -------------------------------- ### Add All Formats from ajv-formats (TypeScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/formats.md Installs all formats provided by the ajv-formats plugin using TypeScript syntax. Ensure ajv-formats is installed as a dependency. ```typescript import Ajv from "ajv" import addFormats from "ajv-formats" const ajv = new Ajv() addFormats(ajv) ``` -------------------------------- ### Method Chaining Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/api.md Demonstrates method chaining for Ajv instance methods like `addSchema`, `addFormat`, and `getSchema`. ```typescript const validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri) ``` -------------------------------- ### Install Ajv v6 for Draft-04 Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/getting-started.md Install Ajv version 6 if you need to use it with JSON Schema draft-04. ```bash npm install ajv@6 ``` -------------------------------- ### Initialize Ajv Instance and Add Schemas (JavaScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/managing-schemas.md Instantiate Ajv and add multiple schemas with string keys. This setup allows for centralized schema management and retrieval. ```javascript const Ajv = require("ajv") const schema_user = require("./schema_user.json") const schema_document = require("./schema_document.json") const ajv = exports.ajv = new Ajv() ajv.addSchema(schema_user, "user") ajv.addSchema(schema_document, "document") ``` -------------------------------- ### Self-Referencing Schema for Binary Tree Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-type-definition.md This example demonstrates a self-referencing schema using 'ref' to define a recursive structure like a binary tree. ```javascript { ref: "tree", definitions: { tree: { properties: { value: {type: "int32"} }, optionalProperties: { left: {ref: "tree"}, right: {ref: "tree"} } } } } ``` -------------------------------- ### Initialize Ajv Instance and Add Schemas (TypeScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/managing-schemas.md Instantiate Ajv and add multiple schemas with string keys in TypeScript. This setup allows for centralized schema management and retrieval. ```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") ``` -------------------------------- ### Compile Schemas During Initialization (JavaScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/managing-schemas.md Compile schemas when the application starts to ensure they are ready for use. This approach is suitable for server-side applications where schemas are known at initialization. ```javascript const Ajv = require("ajv").default const schema_user = require("./schema_user.json") const ajv = new Ajv() const validate_user = ajv.compile(schema_user) // this is just some abstract API framework app.post("/user", async (cxt) => { if (validate_user(cxt.body)) { // create user } else { // report error cxt.status(400) } }) ``` -------------------------------- ### Configure Ajv for Standalone Code Generation with Custom Formats Source: https://github.com/ajv-validator/ajv/blob/master/docs/standalone.md Set `code.source` to true and provide custom format definitions via `code.formats`. This example imports formats from a local file. ```javascript import myFormats from "./my-formats" import Ajv, {_} from "ajv" const ajv = new Ajv({ formats: myFormats, code: { source: true, formats: _`require("./my-formats")`, }, }) ``` -------------------------------- ### Equivalent Schema after $merge or $patch Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/combining-schemas.md This schema represents the equivalent structure after applying either the $merge or $patch operations shown in the previous examples. ```json { type: "object", properties: { p: {type: "string"}, q: {type: "number"} }, additionalProperties: false } ``` -------------------------------- ### Constrained Tuple Schema Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/strict-mode.md This schema correctly defines a tuple with specific types and constraints on its size using `minItems` and `additionalItems`. This is a recommended pattern to avoid potential mistakes with unconstrained tuples. ```json { type: "array", items: [{type: "number"}, {type: "boolean"}], minItems: 2, additionalItems: false // or // maxItems: 2 } ``` -------------------------------- ### Schema Extension using $patch Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/combining-schemas.md The $patch keyword allows extending a schema using JSON Patch operations. This example adds the property 'q' to the source schema. ```json { "$patch": { "source": { "type": "object", "properties": {"p": {"type": "string"}}, "additionalProperties": false }, "with": [{op: "add", path: "/properties/q", value: {type: "number"}}] } } ``` -------------------------------- ### Schema Extension using $merge Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/combining-schemas.md The $merge keyword allows extending a schema by merging a source schema with another schema. This example merges properties 'p' and 'q'. ```json { "$merge": { "source": { "type": "object", "properties": {"p": {"type": "string"}}, "additionalProperties": false }, "with": { "properties": {"q": {"type": "number"}} } } } ``` -------------------------------- ### Const with $data Reference Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md Demonstrates using `const` with a `$data` reference to define equality between different parts of the data. This cannot be achieved with the `enum` keyword. ```javascript { type: "object", properties: { foo: {type: "number"}, bar: {const: {$data: "1/foo"}} } } ``` -------------------------------- ### Object Validation with `additionalProperties` and `anyOf` Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md This example demonstrates combining `additionalProperties: false` with `anyOf` to enforce specific optional properties. The object must not have additional properties beyond those defined in the `anyOf` subschemas or explicitly listed properties. ```javascript { type: "object", properties: { foo: {type: "number"} }, additionalProperties: false, anyOf: [ { properties: { bar: {type: "number"} } }, { properties: { baz: {type: "number"} } } ] } ``` -------------------------------- ### Unconstrained Tuple Schema Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/strict-mode.md This schema defines a tuple with specific types for its first two elements but lacks constraints on its size or additional items. Use `strictTuples` option to warn about such schemas. ```json { type: "array", items: [{type: "number"}, {type: "boolean"}] } ``` -------------------------------- ### anyOf Keyword Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md The `anyOf` keyword validates data against an array of JSON Schemas. Data is valid if it matches *one or more* schemas in the array. Validation stops at the first match. ```javascript { type: "number", anyOf: [{maximum: 3}, {type: "integer"}] } ``` -------------------------------- ### Nested conditional validation with if/then/else Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md Demonstrates nested if/then/else structures for more complex conditional validation rules. This example applies multipleOf checks based on different minimum value conditions. ```javascript { type: "integer", minimum: 1, maximum: 1000, if: {minimum: 100}, then: {multipleOf: 100}, else: { if: {minimum: 10}, then: {multipleOf: 10} } } ``` -------------------------------- ### Import Ajv for JSON Schema draft-04 (JavaScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md Import Ajv from the 'ajv-draft-04' package for using JSON Schema draft-04. This requires installing both 'ajv' and 'ajv-draft-04'. Note that this instance cannot combine multiple JSON Schema versions. ```javascript const Ajv = require("ajv-draft-04") const ajv = new Ajv() ``` -------------------------------- ### Use $data for Dynamic Format Validation Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/combining-schemas.md This example demonstrates using a $data reference to dynamically set the 'format' keyword based on the property name. The $data option must be enabled in Ajv. ```javascript const schema = { additionalProperties: { type: "string", format: {$data: "0#"}, }, } const validData = { "date-time": "1963-06-19T08:30:06.283185Z", email: "joe.bloggs@example.com", } ``` -------------------------------- ### Union Type Schema - Valid Example (with null) Source: https://github.com/ajv-validator/ajv/blob/master/docs/strict-mode.md This schema demonstrates a valid use of the 'type' keyword with a union including 'null', which is permitted even in strict mode. Alternatively, 'nullable: true' can be used. ```json { type: ["object", "null"] } ``` -------------------------------- ### Discriminated Union Schema Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/modifying-data.md Use a discriminated union with the `discriminator` keyword to ensure `removeAdditional` works as expected with `anyOf`/`oneOf`. This approach evaluates only one subschema, preventing unexpected property removal. ```json { "type": "object", "discriminator": {"propertyName": "tag"}, "required": ["tag"], "oneOf": [ { "properties": { "tag": {"const": "foo"}, "foo": {"type": "string"} }, "required": ["foo"], "additionalProperties": false }, { "properties": { "tag": {"const": "bar"}, "bar": {"type": "integer"} }, "required": ["bar"], "additionalProperties": false } ] } ``` -------------------------------- ### Import Ajv for JSON Schema draft-04 (TypeScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md Import Ajv from the 'ajv-draft-04' package for using JSON Schema draft-04 in TypeScript. This requires installing both 'ajv' and 'ajv-draft-04'. Note that this instance cannot combine multiple JSON Schema versions. ```typescript import Ajv from "ajv-draft-04" const ajv = new Ajv() ``` -------------------------------- ### Strict Types - Union Type Refactored with $defs and anyOf Source: https://github.com/ajv-validator/ajv/blob/master/docs/strict-mode.md This refactored example further improves maintainability by defining reusable schema parts in `$defs` and referencing them within `anyOf`, demonstrating a clean way to handle complex union types. ```json { $defs: { item: { type: "number", minimum: 0 } }, anyOf: [ {$ref: "#/\$defs/item"}, { type: "array", items: {$ref: "#/\$defs/item"} }, ] } ``` -------------------------------- ### Get Keyword Definition Source: https://github.com/ajv-validator/ajv/blob/master/docs/api.md Retrieve the definition of an existing keyword using its name. Returns `false` if the keyword is not found. ```typescript const keywordDefinition = ajv.getKeyword("required"); // keywordDefinition will be the definition object or false ``` -------------------------------- ### Ajv Constructor Source: https://github.com/ajv-validator/ajv/blob/master/docs/api.md Instantiate Ajv with optional configuration options. See Options documentation for details. ```APIDOC ## new Ajv(options: object) ### Description Create an Ajv instance with the specified options. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (object) - Optional - Configuration options for Ajv. ### Request Example ```javascript const ajv = new Ajv() ``` ### Response #### Success Response (200) An Ajv instance. #### Response Example ```json { "instance": "Ajv instance" } ``` ``` -------------------------------- ### Not Keyword Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md The `not` keyword validates data against a subschema. The data is considered valid if it is *invalid* according to the specified subschema. ```javascript {type: "number", not: {minimum: 3}} ``` -------------------------------- ### Ajv Initialization with Dynamic Schemas Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/combining-schemas.md Instantiating Ajv with multiple schemas, including one that uses dynamic references, to enable validation against the extended schema. ```javascript import Ajv2019 from "ajv/dist/2019" // const Ajv2019 = require("ajv/dist/2019") const ajv = new Ajv2019({ schemas: [treeSchema, strictTreeSchema], }) const validate = ajv.getSchema("https://example.com/strict-tree") ``` -------------------------------- ### Add $merge and $patch Keywords to Ajv Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/combining-schemas.md To use the $merge and $patch keywords for extending schemas, you need to install and require the 'ajv-merge-patch' package. ```javascript require("ajv-merge-patch")(ajv) ``` -------------------------------- ### Build and Watch Commands Source: https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md Commands for building the project and automatically recompiling TypeScript files on changes. ```bash npm run build ``` ```bash npm run watch ``` -------------------------------- ### Basic Usage of Ajv Source: https://github.com/ajv-validator/ajv/blob/master/README.md Demonstrates how to instantiate Ajv, compile a schema, and validate data. Supports both CommonJS and ESM/TypeScript import. ```javascript // or ESM/TypeScript import import Ajv from "ajv" // Node.js require: 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 data = { foo: 1, bar: "abc", } const validate = ajv.compile(schema) const valid = validate(data) if (!valid) console.log(validate.errors) ``` -------------------------------- ### Define JSON Schema with JSONSchemaType Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/typescript.md Use `JSONSchemaType` to define a schema and get type inference for your data. The compiled validator acts as a type guard. ```typescript import Ajv, {JSONSchemaType} from "ajv" const ajv = new Ajv() interface MyData { foo: number bar?: string } const schema: JSONSchemaType = { type: "object", properties: { foo: {type: "integer"}, bar: {type: "string", nullable: true} }, 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(schema) const data = { foo: 1, bar: "abc" } if (validate(data)) { // data is MyData here console.log(data.foo) } else { console.log(validate.errors) } ``` -------------------------------- ### oneOf Keyword Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md The `oneOf` keyword validates data against an array of JSON Schemas. Data is valid if it matches *exactly one* schema in the array. ```javascript { type: "number", oneOf: [{maximum: 3}, {type: "integer"}] } ``` -------------------------------- ### Load Ajv for JSON Schema (draft-07) in Browser Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/environments.md Include the Ajv v7 UMD bundle for JSON Schema draft-07 and initialize Ajv. This is useful for browser environments where a module system might not be present. ```html ``` -------------------------------- ### Initialize Ajv with All Errors Option Source: https://github.com/ajv-validator/ajv/blob/master/docs/options.md Pass the `allErrors: true` option to the Ajv constructor to report all validation errors instead of stopping at the first one. ```javascript const ajv = new Ajv({allErrors: true}) ``` -------------------------------- ### Const Keyword Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md The `const` keyword validates data against a single, specific value. The data is valid only if it is deeply equal to the keyword's value. ```javascript {const: "foo"} ``` -------------------------------- ### Load Ajv for JSON Schema (draft-2019-09) in Browser Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/environments.md Include the Ajv v2019 UMD bundle for JSON Schema draft-2019-09 and initialize Ajv. This is suitable for browser environments lacking a module system. ```html ``` -------------------------------- ### Enum Keyword Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md The `enum` keyword validates data against an array of unique items. The data is considered valid if it is deeply equal to any item in the array. ```javascript {enum: [2, "foo", {foo: "bar" }, [1, 2, 3]]} ``` -------------------------------- ### Initialize Ajv with Draft-07 Support Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/schema-language.md Import and initialize Ajv for supporting JSON Schema drafts 07 and 06. This is the main export for widely used versions. ```javascript import Ajv from "ajv" const ajv = new Ajv() ``` -------------------------------- ### Instantiate Ajv Source: https://github.com/ajv-validator/ajv/blob/master/docs/api.md Create a new instance of the Ajv validator. See Options for configuration details. ```javascript const ajv = new Ajv() ``` -------------------------------- ### Non-Discriminated Union Schema Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/modifying-data.md This schema demonstrates a non-discriminated union where `removeAdditional: true` can lead to unexpected validation results due to properties being removed before all subschemas are evaluated. ```json { "type": "object", "oneOf": [ { "properties": { "foo": {"type": "string"} }, "required": ["foo"], "additionalProperties": false }, { "properties": { "bar": {"type": "integer"} }, "required": ["bar"], "additionalProperties": false } ] } ``` -------------------------------- ### Compile Schemas Using addSchema Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/combining-schemas.md Compile schemas by first adding the referenced schemas to the Ajv instance using `addSchema`, then compiling the main schema. This method is useful when schemas are added incrementally. ```javascript const ajv = new Ajv() const validate = ajv.addSchema(defsSchema).compile(schema) ``` -------------------------------- ### Initialize Ajv with Draft-2019-09 Support Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/schema-language.md Use this export to enable support for JSON Schema drafts 2019-09 and 2020-12, which includes features like 'unevaluatedProperties' and dynamic recursive references. ```javascript import Ajv2019 from "ajv/dist/2019" const ajv = new Ajv2019() ``` -------------------------------- ### Compile Schemas During Initialization (TypeScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/managing-schemas.md Compile schemas using TypeScript for type safety. Ensure schemas are compiled once during application startup for optimal performance. ```typescript import Ajv from "ajv" import * as schema_user from "./schema_user.json" const ajv = new Ajv() const validate_user = ajv.compile(schema_user) interface User { username: string } // this is just some abstract API framework app.post("/user", async (cxt) => { if (validate_user(cxt.body)) { // create user } else { // report error cxt.status(400) } }) ``` -------------------------------- ### Strict Types - Union Type Refactored with anyOf Source: https://github.com/ajv-validator/ajv/blob/master/docs/strict-mode.md This example shows how to refactor a schema violating `strictTypes` into an equivalent structure using `anyOf`, making it compliant and easier to maintain. ```json { anyOf: [ { type: "number", minimum: 0, }, { type: "array", items: { type: "number", minimum: 0, }, }, ] } ``` -------------------------------- ### Load Ajv for JSON Type Definition (JTD) in Browser Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/environments.md Include the Ajv JTD UMD bundle and initialize Ajv. This is recommended for browser environments without a module system. ```html ``` -------------------------------- ### Union Type Schema - Valid Example (nullable) Source: https://github.com/ajv-validator/ajv/blob/master/docs/strict-mode.md This schema uses the 'nullable: true' property to achieve the same effect as a union type including 'null', which is a valid alternative in strict mode. ```json { type: "object", nullable: true } ``` -------------------------------- ### Compile Schema Using $id (JavaScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/managing-schemas.md If a schema has an `$id` attribute, you can use `getSchema` with the `$id` or `compile` directly. `compile` will also add the schema to the cache. ```javascript const schema_user = require("./schema_user.json") const validate = ajv.getSchema("https://example.com/user.json") || ajv.compile(schema_user) ``` -------------------------------- ### Compile Schemas by Passing All to Ajv Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/combining-schemas.md Compile schemas that reference each other by passing all schema objects to the Ajv constructor's `schemas` option. This allows Ajv to resolve references internally. ```javascript const ajv = new Ajv({schemas: [schema, defsSchema]}) const validate = ajv.getSchema("http://example.com/schemas/schema.json") ``` -------------------------------- ### Strict Types - Union Type Violation Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/strict-mode.md This schema violates the `strictTypes` option by using a union of 'number' and 'array' types with differing constraints. Refactor using `anyOf` for clarity and maintainability. ```json { type: ["number", "array"], minimum: 0, items: { type: "number", minimum: 0 } } ``` -------------------------------- ### Configure Standalone Code with Custom Formats (TypeScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/formats.md Configures Ajv for standalone code generation, incorporating custom formats from './my_formats'. The '_`require`' syntax is used for module path specification. ```typescript import Ajv, {_} from "ajv" const ajv = new Ajv({code: {formats: _`require("./my_formats")`}}) ``` -------------------------------- ### Import Ajv for JSON Schema draft-07 (JavaScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md Import the default Ajv class for using JSON Schema draft-07. This version is recommended for better performance unless newer features are required. ```javascript const Ajv = require("ajv") const ajv = new Ajv() ``` -------------------------------- ### Configure Ajv to Ignore Unknown Formats Source: https://github.com/ajv-validator/ajv/blob/master/docs/strict-mode.md When initializing Ajv, you can use the `formats` option to specify which formats should be ignored. Setting a format's definition to `true` will cause it to be ignored during validation. ```javascript const ajv = new Ajv({formats: { reserved: true }) ``` -------------------------------- ### Configure Ajv for ES5 Environments Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/environments.md Instantiate Ajv with options to generate ES5 compatible code. This is necessary for older JavaScript environments like Internet Explorer 11. ```javascript const ajv = new Ajv({code: {es5: true}}) ``` -------------------------------- ### Handling Validation Errors with DefinedError Type Source: https://github.com/ajv-validator/ajv/blob/master/docs/api.md Demonstrates how to iterate through validation errors and access specific parameters based on the keyword. This example uses a type assertion to `DefinedError[]` for accessing common error parameters. ```typescript const ajv = new Ajv() const validate = ajv.compile(schema) if (validate(data)) { // data is MyData here // ... } else { // DefinedError is a type for all pre-defined keywords errors, // validate.errors has type ErrorObject[] - to allow user-defined keywords with any error parameters. // Users can extend DefinedError to include the keywords errors they defined. for (const err of validate.errors as DefinedError[]) { switch (err.keyword) { case "maximum": console.log(err.limit) break case "pattern": console.log(err.pattern) break // ... } } } ``` -------------------------------- ### Add Schema on Demand if Not Present (JavaScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/managing-schemas.md Check if a schema is already compiled using `getSchema`. If not, add and compile it. This approach is useful when dealing with a large number of schemas. ```javascript const schema_user = require("./schema_user.json") let validate = ajv.getSchema("user") if (!validate) { ajv.addSchema(schema_user, "user") validate = ajv.getSchema("user") } ``` -------------------------------- ### Asynchronously Compile and Validate Schema Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/managing-schemas.md Use `compileAsync` to load schemas on demand. Provide a `loadSchema` function that returns a Promise resolving to the schema. This is useful for schemas stored remotely or in a database. ```javascript const ajv = new Ajv({loadSchema: loadSchema}) ajv.compileAsync(schema).then(function (validate) { const valid = validate(data) // ... }) async function loadSchema(uri) { const res = await request.json(uri) if (res.statusCode >= 400) throw new Error("Loading error: " + res.statusCode) return res.body } ``` -------------------------------- ### Union Type Schema - Invalid Example Source: https://github.com/ajv-validator/ajv/blob/master/docs/strict-mode.md This schema uses a union of 'string' and 'number' types directly in the 'type' keyword, which is prohibited by default in strict mode. Use `allowUnionTypes: true` to permit this or refactor using `anyOf`. ```json { type: ["string", "number"] } ``` -------------------------------- ### Configure Standalone Code with Custom Formats (JavaScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/formats.md Configures Ajv to generate standalone validation code that includes custom formats defined in './my_formats'. The '_`require`' syntax is used to pass the module path. ```javascript const {default: Ajv, _} = require("ajv") const ajv = new Ajv({code: {formats: _`require("./my_formats")`}}) ``` -------------------------------- ### Generate standalone validation for multiple schemas using JS library Source: https://github.com/ajv-validator/ajv/blob/master/docs/standalone.md Generate standalone validation code for multiple schemas using the Ajv JS library. For CJS, this generates an exports array. This example uses ES6 and CJS exports. ```javascript const fs = require("fs") const path = require("path") const Ajv = require("ajv") const standaloneCode = require("ajv/dist/standalone").default const schemaFoo = { $id: "#/definitions/Foo", $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { foo: {"$ref": "#/definitions/Bar"} } } const schemaBar = { $id: "#/definitions/Bar", $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { bar: {type: "string"}, }, "required": ["bar"] } // For CJS, it generates an exports array, will generate // `exports["#//definitions/Foo"] = ...;exports["#//definitions/Bar"] = ... ; const ajv = new Ajv({schemas: [schemaFoo, schemaBar], code: {source: true}}) let moduleCode = standaloneCode(ajv) // Now you can write the module code to file fs.writeFileSync(path.join(__dirname, "../consume/validate-cjs.js"), moduleCode) ``` -------------------------------- ### Generate standalone validation for a single schema using JS library Source: https://github.com/ajv-validator/ajv/blob/master/docs/standalone.md Generate standalone validation code for a single schema using the Ajv JS library. The generated code will have a default export. This example uses ES6 and CJS exports. ```javascript const fs = require("fs") const path = require("path") const Ajv = require("ajv") const standaloneCode = require("ajv/dist/standalone").default const schema = { $id: "https://example.com/bar.json", $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { bar: {type: "string"}, }, "required": ["bar"] } // The generated code will have a default export: // `module.exports = ;module.exports.default = ;` const ajv = new Ajv({code: {source: true}}) const validate = ajv.compile(schema) let moduleCode = standaloneCode(ajv, validate) // Now you can write the module code to file fs.writeFileSync(path.join(__dirname, "../consume/validate-cjs.js"), moduleCode) ``` -------------------------------- ### Coercing Array Item Types Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/modifying-data.md Use `coerceTypes: "array"` to specifically coerce types within arrays. For example, a string '1' can be coerced to a number 1 within an array of numbers. This option modifies the original data. ```javascript const ajv = new Ajv({coerceTypes: "array"}) const schema = { properties: { foo: {type: "array", items: {type: "number"}}, bar: {type: "boolean"}, }, } const data = {foo: "1", bar: ["false"]} const validate = ajv.compile(schema) console.log(validate(data)) // true console.log(data) // { "foo": [1], "bar": false } ``` -------------------------------- ### Ajv Default Options Structure Source: https://github.com/ajv-validator/ajv/blob/master/docs/options.md This object shows the default configuration values for Ajv. It is recommended to only pass options that differ from these defaults. ```javascript // see types/index.ts for actual types const defaultOptions = { // strict mode options (NEW) strict: undefined, // * strictSchema: true, // * strictNumbers: true, // * strictTypes: "log", // * strictTuples: "log", // * strictRequired: false, // * allowUnionTypes: false, // * allowMatchingProperties: false, // * validateFormats: true, // * // validation and reporting options: "$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, // *, function(uri: string): Promise {} // options to modify validated data: removeAdditional: false, useDefaults: false, // * coerceTypes: false, // * // advanced options: meta: true, validateSchema: true, addUsedSchema: true, inlineRefs: true, passContext: false, loopRequired: 200, // * loopEnum: 200, // NEW ownProperties: false, multipleOfPrecision: undefined, // * messages: true, // false with JTD uriResolver: undefined, code: { // NEW es5: false, esm: false, lines: false, source: false, process: undefined, // (code: string) => string optimize: true, regExp: RegExp }, } ``` -------------------------------- ### Array items Validation with prefixItems (Draft 2020-12) Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md In draft-2020-12, when `prefixItems` is used, `items` defines the schema for elements starting from the index after the `prefixItems`. This allows for variable-length arrays where the initial elements conform to `prefixItems` and subsequent elements conform to `items`. ```json { "type": "array", "prefixItems": [{"type": "integer"}, {"type": "integer"}], "items": {"type": "string"} } ``` -------------------------------- ### Error Parameters for `dependencies` Source: https://github.com/ajv-validator/ajv/blob/master/docs/api.md Details the `params` object for the `dependencies` keyword, including the dependent property, missing dependencies, and the count of required dependencies. ```typescript type ErrorParams = { property: string // dependent property, missingProperty: string // required missing dependency - only the first one is reported deps: string // required dependencies, comma separated list as a string (TODO change to string[]) depsCount: number // the number of required dependencies } ``` -------------------------------- ### Define 'range' and 'exclusiveRange' keywords Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/user-keywords.md This example demonstrates defining custom keywords 'range' and 'exclusiveRange' using the `compile` option. The 'range' keyword validates if a number falls within a specified range, and 'exclusiveRange' modifies this to check for strict inequality. Use this when you need custom validation logic not covered by standard keywords. ```javascript ajv.addKeyword({ keyword: "range", type: "number", schemaType: "array", implements: "exclusiveRange", compile: ([min, max], parentSchema) => parentSchema.exclusiveRange === true ? (data) => data > min && data < max : (data) => data >= min && data <= max, }) const schema = {range: [2, 4], exclusiveRange: true} const validate = ajv.compile(schema) console.log(validate(2.01)) // true console.log(validate(3.99)) // true console.log(validate(2)) // false console.log(validate(4)) // false ``` -------------------------------- ### ajv.compileAsync Source: https://github.com/ajv-validator/ajv/blob/master/docs/api.md An asynchronous version of the `compile` method. It loads missing remote schemas using an asynchronous function provided in `options.loadSchema`. It returns a Promise that resolves to a validation function. ```APIDOC ## ajv.compileAsync(schema: object, meta?: boolean): Promise < Function > ### Description Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: - missing schema can't be loaded (`loadSchema` returns a Promise that rejects). - a schema containing a missing reference is loaded, but the reference cannot be resolved. - schema (or some loaded/referenced schema) is invalid. The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. You can asynchronously compile meta-schema by passing `true` as the second parameter. Similarly to `compile`, it can return type guard in typescript. See example in [Asynchronous schema loading](./guide/managing-schemas.md#asynchronous-schema-loading). ``` -------------------------------- ### Define Schema Reference Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-type-definition.md Use the 'ref' form to reference a schema defined in the root 'definitions' object. This allows for reusable schema components. ```javascript { properties: { propFoo: {ref: "foo", nullable: true} }, definitions: { foo: {type: "string"} } } ``` -------------------------------- ### Support draft-06 and draft-07 Schemas (JavaScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-schema.md Configure an Ajv instance to support both JSON Schema draft-06 and draft-07. This involves importing the default Ajv and adding the draft-06 meta-schema. ```javascript const Ajv = require("ajv") const draft6MetaSchema = require("ajv/dist/refs/json-schema-draft-06.json") const ajv = new Ajv() ajv.addMetaSchema(draft6MetaSchema) ``` -------------------------------- ### Import JTD Ajv Class (JavaScript) Source: https://github.com/ajv-validator/ajv/blob/master/docs/json-type-definition.md Import the specific Ajv class for JTD schemas in JavaScript. ```javascript const Ajv = require("ajv/dist/jtd") const ajv = new Ajv() ``` -------------------------------- ### Error Parameters for String and Collection Keywords Source: https://github.com/ajv-validator/ajv/blob/master/docs/api.md Defines the `params` object for keywords related to string length (`minLength`, `maxLength`) and collection size (`minItems`, `maxItems`, `minProperties`, `maxProperties`). ```typescript type ErrorParams = {limit: number} // keyword value ``` -------------------------------- ### Define Schemas with $ref Source: https://github.com/ajv-validator/ajv/blob/master/docs/guide/combining-schemas.md Define schemas that reference definitions from other schema files using the `$ref` keyword. Ensure each schema has a unique `$id` for proper resolution. ```javascript const schema = { $id: "http://example.com/schemas/schema.json", type: "object", properties: { foo: {$ref: "defs.json#/definitions/int"}, bar: {$ref: "defs.json#/definitions/str"}, }, } const defsSchema = { $id: "http://example.com/schemas/defs.json", definitions: { int: {type: "integer"}, str: {type: "string"}, }, } ```