Movatterモバイル変換


[0]ホーム

URL:


Ajv JSON schema validatorAjv JSON schema validator

# Ajv options

# Usage

This page describes properties of the options object that can be passed to Ajv constructor.

For example, to report all validation errors (rather than failing on the first errors) you should passallErrors option to constructor:

const ajv=newAjv({allErrors:true})

# Option defaults

Do NOT pass default options

Passing the value below for some of the options is equivalent to not passing this option at all. There is no need to pass default option values - it is recommended to only pass option values that are different from defaults.

// see types/index.ts for actual typesconst 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,// NEWownProperties:false,multipleOfPrecision:undefined,// *messages:true,// false with JTDuriResolver:undefined,code:{// NEWes5:false,esm:false,lines:false,source:false,process:undefined,// (code: string) => stringoptimize:true,regExp: RegExp},}

* only with JSON Schema

** only with JSON Type Definition

# Strict mode optionsv7

# strict

By default Ajv executes in strict mode, that is designed to prevent any unexpected behaviours or silently ignored mistakes in schemas (seeStrict Mode for more details). It does not change any validation results, but it makes some schemas invalid that would be otherwise valid according to JSON Schema specification.

Option values:

  • true - throw an exception when any strict mode restriction is violated.
  • "log" - log warning when any strict mode restriction is violated.
  • false - ignore all strict mode violations.
  • undefined (default) - use defaults for options strictSchema, strictNumbers, strictTypes, strictTuples and strictRequired.

# strictSchema

Prevent unknown keywords, formats etc. (seeStrict schema)

Option values:

  • true (default) - throw an exception when any strict schema restriction is violated.
  • "log" - log warning when any strict schema restriction is violated.
  • false - ignore all strict schema violations.

# strictNumbers

Whether to acceptNaN andInfinity as number types during validation.

Option values:

  • true (default) - fail validation ifNaN orInfinity is passed where number is expected.
  • false - allowNaN andInfinity as number.

# strictTypes

SeeStrict types

Option values:

  • true - throw an exception when any strict types restriction is violated.
  • "log" (default) - log warning when any strict types restriction is violated.
  • false - ignore all strict types violations.

# strictTuples

SeeUnconstrained tuples

Option values:

  • true - throw an exception when any strict tuples restriction is violated.
  • "log" (default) - log warning when any strict tuples restriction is violated.
  • false - ignore all strict tuples violations.

# strictRequired

SeeDefined required properties

Option values:

  • true - throw an exception when strict required restriction is violated.
  • "log" - log warning when strict required restriction is violated.
  • false (default) - ignore strict required violations.

# allowUnionTypes

Pass true to allow using multiple non-null types in "type" keyword (one ofstrictTypes restrictions). seeStrict types

# allowMatchingProperties

Pass true to allow overlap between "properties" and "patternProperties". Does not affect other strict mode restrictions. SeeStrict Mode.

# validateFormats

Format validation.

Option values:

  • true (default) - validate formats (seeFormats). Instrict mode unknown formats will throw exception during schema compilation (and fail validation in case format keyword value is$data reference).
  • false - do not validate any format keywords (TODO they will still collect annotations once supported).

# Validation and reporting options

# $data

Support$data references. Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. SeeAPI.

# allErrors

Check all rules collecting all errors. Default is to return after the first error.

# verbose

Include the reference to the part of the schema (schema andparentSchema) and validated data in errors (false by default).

# discriminator

Supportdiscriminator keyword fromOpenAPI specification(opens new window).

# unicodeRegExp

By default Ajv uses unicode flag "u" with "pattern" and "patternProperties", as per JSON Schema spec. SeeRegExp.prototype.unicode(opens new window) .

Option values:

  • true (default) - use unicode flag "u".
  • false - do not use flag "u".

# timestampJTD only

Defines which Javascript types will be accepted for theJTD timestamp type.

By default Ajv will accept both Date objects andRFC3339(opens new window) strings. You can specify allowed values with the optiontimestamp: "date" ortimestamp: "string".

# parseDateJTD only

Defines how date-time strings are parsed byJTD parsers. By default Ajv parses date-time strings as string. UseparseDate: true to parse them as Date objects.

# allowDateJTD only

Defines how date-time strings are parsed and validated. By default Ajv only allows full date-time strings, as required by JTD specification. UseallowDate: true to allow date strings both for validation and for parsing.

Option allowDate is not portable

This option makes JTD validation and parsing more permissive and non-standard. The date strings without time part will be accepted by Ajv, but will be rejected by other JTD validators.

# specialNumbersJTD only

Defines how special case numbersInfinity,-Infinity andNaN are handled.

Option values:

  • "fast" - (default): Do not treat special numbers differently to normal numbers. This is the fastest method but also can produce invalid JSON if the data contains special numbers.
  • "null" - Special numbers will be serialized tonull which is the correct behavior according to the JSON spec and is also the same behavior asJSON.stringify.

The default behavior can produce invalid JSON

UsingspecialNumbers: "fast" or undefined can produce invalid JSON when there are any special case numbers in the data.

# int32rangeJTD only

Can be used to disable range checking forint32 anduint32 types.

By default Ajv limits the range of these types to[-2**31, 2**31 - 1] forint32 and to[0, 2**32-1] foruint32 when validating and parsing.

With optionint32range: false Ajv only requires thatuint32 is non-negative, otherwise does not check the range. Parser will limit the number size to 16 digits (approx.2**53 - safe integer range).

Option int32range is not portable

This option makes JTD validation and parsing more permissive and non-standard. The integers within a wider range will be accepted by Ajv, but will be rejected by other JTD validators.

# $comment

Log or pass the value of$comment keyword to a function.

Option values:

  • false (default): ignore $comment keyword.
  • true: log the keyword value to console.
  • function: pass the keyword value, its schema path and root schema to the specified function

# formats

An object with format definitions. Keys and values will be passed toaddFormat method. Passtrue as format definition to ignore some formats.

# keywords

An array of keyword definitions or strings. Values will be passed toaddKeyword method.

# schemas

An array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the methodaddSchema(value, key) will be called for each schema in this object.

# logger

Sets the logging method. Default is the globalconsole object that should have methodslog,warn anderror. SeeError logging.

Option values:

  • logger instance - it should have methodslog,warn anderror. If any of these methods is missing an exception will be thrown.
  • false - logging is disabled.

# loadSchema

Asynchronous function that will be used to load remote schemas whencompileAsyncmethod is used and some reference is missing (optionmissingRefs should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example inAsynchronous compilation.

# Options to modify validated data

# removeAdditional

Remove additional properties - see example inRemoving additional properties.

This option is not used if schema is added withaddMetaSchema method.

Option values:

  • false (default) - not to remove additional properties
  • "all" - all additional properties are removed, regardless ofadditionalProperties keyword in schema (and no validation is made for them).
  • true - only additional properties withadditionalProperties keyword equal tofalse are removed.
  • "failing" - additional properties that fail schema validation will be removed (whereadditionalProperties keyword isfalse or schema).

# useDefaults

Replace missing or undefined properties and items with the values from correspondingdefault keywords. Default behaviour is to ignoredefault keywords. This option is not used if schema is added withaddMetaSchema method.

See examples inAssigning defaults.

Option values:

  • false (default) - do not use defaults
  • true - insert defaults by value (object literal is used).
  • "empty" - in addition to missing or undefined, use defaults for properties and items that are equal tonull or"" (an empty string).

# coerceTypes

Change data type of data to matchtype keyword. See the example inCoercing data types andcoercion rules.

Option values:

  • false (default) - no type coercion.
  • true - coerce scalar data types.
  • "array" - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema).

# Advanced options

# meta

Addmeta-schema(opens new window) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no$schema keyword. This default meta-schema MUST have$schema keyword.

# validateSchema

Validate added/compiled schemas against meta-schema (true by default).$schema property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added withaddMetaSchema method.

Option values:

  • true (default) - if the validation fails, throw the exception.
  • "log" - if the validation fails, log error.
  • false - skip schema validation.

# addUsedSchema

By default methodscompile andvalidate add schemas to the instance if they have$id (orid) property that doesn't start with "#". If$id is present and it is not unique the exception will be thrown. Set this option tofalse to skip adding schemas to the instance and the$id uniqueness check when these methods are used. This option does not affectaddSchema method.

# inlineRefs

Affects compilation of referenced schemas.

Option values:

  • true (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - it improves performance.
  • false - to not inline referenced schemas (they will always be compiled as separate functions).
  • integer number - to limit the maximum number of keywords of the schema that will be inlined (to balance the total size of compiled functions and performance).

# passContext

Pass validation context tocompile andvalidate keyword functions. If this option istrue and you pass some context to the compiled validation function withvalidate.call(context, data), thecontext will be available asthis in your keywords. By defaultthis is Ajv instance.

# loopRequired

By defaultrequired keyword is compiled into a single expression (or a sequence of statements inallErrors mode) up to 200 required properties. Pass integer to set a different number of properties above whichrequired keyword will be validated in a loop (with a smaller validation function size and worse performance).

# loopEnumv7

By defaultenum keyword is compiled into a single expression with up to 200 allowed values. Pass integer to set the number of values above whichenum keyword will be validated in a loop (with a smaller validation function size and worse performance).

# ownProperties

By default Ajv iterates over all enumerable object properties; when this option istrue only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst.

# multipleOfPrecision

By defaultmultipleOf keyword is validated by comparing the result of division withparseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue#84(opens new window)). If you need to use fractional dividers set this option to some positive integer N to havemultipleOf validated using this formula:Math.abs(Math.round(division) - division) < 1e-N (it is slower but allows for float arithmetic deviations).

# messages

Include human-readable messages in errors.true by default.false can be passed when messages are generated outside of Ajv code (e.g. withajv-i18n(opens new window)).

# uriResolver

By defaulturiResolver is undefined and relies on the embedded uriResolverfast-uri(opens new window). Pass an object that satisfies the interfaceUriResolver(opens new window) to be used in replacement. One alternative isuri-js(opens new window).

# codev7

Code generation options:

typeCodeOptions={  es5?:boolean// to generate es5 code - by default code is es6, with "for-of" loops, "let" and "const"  esm?:boolean// how functions should be exported - by default CJS is used, so the validate function(s)// file can be `required`. Set this value to true to export the validate function(s) as ES Modules, enabling// bunlers to do their job.  lines?:boolean// add line-breaks to code - to simplify debugging of generated functions  source?:boolean// add `source` property (see Source below) to validating function.  process?:(code:string, schema?: SchemaEnv)=>string// an optional function to process generated code// before it is passed to Function constructor.// It can be used to either beautify or to transpile code.  optimize?:boolean|number// code optimization flag or number of passes, 1 pass by default,// code optimizations reduce the size of the generated code (bytes, based on the tests) by over 10%,// the number of code tree nodes by nearly 17%.// You would almost never need more than one optimization pass, unless you have some really complex schemas -// the second pass in the tests (it has quite complex schemas) only improves optimization by less than 0.1%.// See [Code optimization](./codegen.md#code-optimization) for details.  formats?: Code// Code snippet created with `_` tagged template literal that contains all format definitions,// it can be the code of actual definitions or `require` call:// _`require("./my-formats")`  regExp: RegExpEngine// Pass non-standard RegExp engine to mitigate ReDoS, e.g. node-re2.// During validation of a schema, code.regExp will be// used to match strings against regular expressions.// The supplied function must support the interface:// regExp(regex, unicodeFlag).test(string) => boolean}typeSource={  code:string// unlike func.toString() it includes assignments external to function scope  scope: Scope// see Code generation (TODO)}

API Reference JSON Schema


[8]ページ先頭

©2009-2025 Movatter.jp