# Ajv 选项
¥Ajv options
# 用法
¥Usage
本页描述了可以传递给 Ajv 构造函数的选项对象的属性。
¥This page describes properties of the options object that can be passed to Ajv constructor.
例如,要报告所有校验错误(而不是在第一个错误时失败),你应该将 allErrors
选项传递给构造函数:
¥For example, to report all validation errors (rather than failing on the first errors) you should pass allErrors
option to constructor:
const ajv = new Ajv({allErrors: true})
# 选项默认值
¥Option defaults
不要通过默认选项
为某些选项传递以下值相当于根本不传递此选项。无需传递默认选项值 - 建议仅传递与默认值不同的选项值。
¥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 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
},
}
* 仅适用于 JSON 架构
¥* only with JSON Schema
** 仅适用于 JSON 类型定义
¥** only with JSON Type Definition
# 严格模式选项
¥Strict mode options
v7# strict
默认情况下,Ajv 以严格结构执行,旨在防止结构中的任何意外行为或默默忽略的错误(有关更多详细信息,请参阅 严格模式)。它不会更改任何校验结果,但会使一些根据 JSON 结构规范本来有效的结构无效。
¥By default Ajv executes in strict mode, that is designed to prevent any unexpected behaviours or silently ignored mistakes in schemas (see Strict 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
- 当违反任何严格模式限制时抛出异常。¥
true
- throw an exception when any strict mode restriction is violated."log"
- 当违反任何严格结构限制时记录警告。¥
"log"
- log warning when any strict mode restriction is violated.false
- 忽略所有严格结构违规。¥
false
- ignore all strict mode violations.undefined
(default) - 使用选项 strictSchema、strictNumbers、strictTypes、strictTuples 和 strictRequired 的默认值。¥
undefined
(default) - use defaults for options strictSchema, strictNumbers, strictTypes, strictTuples and strictRequired.
# strictSchema
防止未知的关键字、格式等(参见 严格的结构)
¥Prevent unknown keywords, formats etc. (see Strict schema)
选项值:
¥Option values:
true
(default) - 当违反任何严格的模式限制时抛出异常。¥
true
(default) - throw an exception when any strict schema restriction is violated."log"
- 当违反任何严格的结构限制时记录警告。¥
"log"
- log warning when any strict schema restriction is violated.false
- 忽略所有严格的结构违规。¥
false
- ignore all strict schema violations.
# strictNumbers
校验期间是否接受 NaN
和 Infinity
作为数字类型。
¥Whether to accept NaN
and Infinity
as number types during validation.
选项值:
¥Option values:
true
(default) - 如果NaN
或Infinity
在预期数字处通过,则校验失败。¥
true
(default) - fail validation ifNaN
orInfinity
is passed where number is expected.false
- 允许NaN
和Infinity
作为数字。¥
false
- allowNaN
andInfinity
as number.
# strictTypes
见 严格类型
¥See Strict types
选项值:
¥Option values:
true
- 当违反任何严格的类型限制时抛出异常。¥
true
- throw an exception when any strict types restriction is violated."log"
(default) - 当违反任何严格类型限制时记录警告。¥
"log"
(default) - log warning when any strict types restriction is violated.false
- 忽略所有严格类型违规。¥
false
- ignore all strict types violations.
# strictTuples
见 无约束元组
¥See Unconstrained tuples
选项值:
¥Option values:
true
- 当违反任何严格的元组限制时抛出异常。¥
true
- throw an exception when any strict tuples restriction is violated."log"
(default) - 当违反任何严格的元组限制时记录警告。¥
"log"
(default) - log warning when any strict tuples restriction is violated.false
- 忽略所有严格的元组违规。¥
false
- ignore all strict tuples violations.
# strictRequired
见 定义所需的属性
¥See Defined required properties
选项值:
¥Option values:
true
- 当违反严格的要求限制时抛出异常。¥
true
- throw an exception when strict required restriction is violated."log"
- 当违反严格要求的限制时记录警告。¥
"log"
- log warning when strict required restriction is violated.false
(default) - ignore strict required violations.
# allowUnionTypes
传递 true 以允许在 "type" 关键字中使用多个非空类型(strictTypes
限制之一)。参见 严格类型
¥Pass true to allow using multiple non-null types in "type" keyword (one of strictTypes
restrictions). see Strict types
# allowMatchingProperties
传递 true 以允许 "properties" 和 "patternProperties" 之间重叠。不影响其他严格结构限制。参见 严格模式。
¥Pass true to allow overlap between "properties" and "patternProperties". Does not affect other strict mode restrictions. See Strict Mode.
# validateFormats
格式校验。
¥Format validation.
选项值:
¥Option values:
true
(default) - validate formats (see Formats).在 严格模式 中,未知格式将在结构编译期间引发异常(并且在格式关键字值为 $data 参考 的情况下校验失败)。¥
true
(default) - validate formats (see Formats). In strict mode unknown formats will throw exception during schema compilation (and fail validation in case format keyword value is $data reference).false
- 不校验任何格式关键字(TODO 一旦支持,它们仍然会收集注释)。¥
false
- do not validate any format keywords (TODO they will still collect annotations once supported).
# 校验和报告选项
¥Validation and reporting options
# $data
支持 $data references。默认添加的草案 6 元结构将被扩展以允许它们。如果你想使用另一个元结构,你需要使用 $dataMetaSchema 方法来添加对 $data 引用的支持。参见 API。
¥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. See API.
# allErrors
检查所有规则收集所有错误。默认是在第一个错误后返回。
¥Check all rules collecting all errors. Default is to return after the first error.
# verbose
包括对结构部分(schema
和 parentSchema
)的引用以及错误中已校验的数据(默认为 false)。
¥Include the reference to the part of the schema (schema
and parentSchema
) and validated data in errors (false by default).
# discriminator
从 开放 API 规范 (opens new window) 开始支持 鉴别器关键字。
¥Support discriminator keyword from OpenAPI specification (opens new window).
# unicodeRegExp
默认情况下,Ajv 根据 JSON 结构规范使用 unicode 标志 "u" 以及 "pattern" 和 "patternProperties"。参见 RegExp.prototype.unicode (opens new window)。
¥By default Ajv uses unicode flag "u" with "pattern" and "patternProperties", as per JSON Schema spec. See RegExp.prototype.unicode (opens new window) .
选项值:
¥Option values:
true
(default) - use unicode flag "u"。false
- 不要使用标志 "u"。¥
false
- do not use flag "u".
# timestamp
JTD only定义 JTD 时间戳类型 将接受哪些 Javascript 类型。
¥Defines which Javascript types will be accepted for the JTD timestamp type.
默认情况下,Ajv 将接受 Date 对象和 RFC3339 (opens new window) 字符串。你可以使用选项 timestamp: "date"
或 timestamp: "string"
指定允许的值。
¥By default Ajv will accept both Date objects and RFC3339 (opens new window) strings. You can specify allowed values with the option timestamp: "date"
or timestamp: "string"
.
# parseDate
JTD only定义 JTD 解析器 如何解析日期时间字符串。默认情况下,Ajv 将日期时间字符串解析为字符串。使用 parseDate: true
将它们解析为 Date 对象。
¥Defines how date-time strings are parsed by JTD parsers. By default Ajv parses date-time strings as string. Use parseDate: true
to parse them as Date objects.
# allowDate
JTD only定义如何解析和校验日期时间字符串。默认情况下,Ajv 仅允许完整的日期时间字符串,如 JTD 规范的要求。使用 allowDate: true
允许日期字符串用于校验和解析。
¥Defines how date-time strings are parsed and validated. By default Ajv only allows full date-time strings, as required by JTD specification. Use allowDate: true
to allow date strings both for validation and for parsing.
选项 allowDate 不可移植
此选项使 JTD 校验和解析更加宽松和非标准。没有时间部分的日期字符串将被 Ajv 接受,但将被其他 JTD 校验器拒绝。
¥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.
# int32range
JTD only可用于禁用 int32
和 uint32
类型的范围检查。
¥Can be used to disable range checking for int32
and uint32
types.
默认情况下,在校验和解析时,Ajv 将这些类型的范围限制为 [-2**31, 2**31 - 1]
(对于 int32
)和 [0, 2**32-1]
(对于 uint32
)。
¥By default Ajv limits the range of these types to [-2**31, 2**31 - 1]
for int32
and to [0, 2**32-1]
for uint32
when validating and parsing.
使用选项 int32range: false
Ajv 仅要求 uint32
为非负数,否则不检查范围。解析器会将数字大小限制为 16 位(大约 2**53
- 安全整数范围)。
¥With option int32range: false
Ajv only requires that uint32
is non-negative, otherwise does not check the range. Parser will limit the number size to 16 digits (approx. 2**53
- safe integer range).
选项 int32range 不可移植
此选项使 JTD 校验和解析更加宽松和非标准。更大范围内的整数将被 Ajv 接受,但会被其他 JTD 校验器拒绝。
¥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
将 $comment
关键字的值记录或传递给函数。
¥Log or pass the value of $comment
keyword to a function.
选项值:
¥Option values:
false
(默认):ignore $comment keyword.¥
false
(default): ignore $comment keyword.true
:将关键字值记录到控制台。¥
true
: log the keyword value to console.function:将关键字值、其结构路径和根结构传递给指定的函数
¥function: pass the keyword value, its schema path and root schema to the specified function
# formats
具有格式定义的对象。键和值将传递给 addFormat
方法。传递 true
作为格式定义以忽略某些格式。
¥An object with format definitions. Keys and values will be passed to addFormat
method. Pass true
as format definition to ignore some formats.
# keywords
关键字定义或字符串的数组。值将传递给 addKeyword
方法。
¥An array of keyword definitions or strings. Values will be passed to addKeyword
method.
# schemas
将添加到实例的结构数组或对象。如果你传递数组,结构中必须包含 ID。当对象被传递时,将为此对象中的每个结构调用方法 addSchema(value, key)
。
¥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 method addSchema(value, key)
will be called for each schema in this object.
# logger
设置记录方法。默认是全局 console
对象,该对象应具有方法 log
、warn
和 error
。参见 错误记录。
¥Sets the logging method. Default is the global console
object that should have methods log
, warn
and error
. See Error logging.
选项值:
¥Option values:
logger instance - 它应该有方法
log
、warn
和error
。如果缺少任何一个方法,就会抛出异常。¥logger instance - it should have methods
log
,warn
anderror
. If any of these methods is missing an exception will be thrown.false
- 日志记录已禁用。¥
false
- logging is disabled.
# loadSchema
当使用 compileAsync
method 并且缺少某些引用时,将用于加载远程结构的异步函数(选项 missingRefs
不应该是 'fail' 或 'ignore')。此函数应接受远程结构 uri 作为参数并返回解析为结构的 Promise。参见 异步编译 中的示例。
¥Asynchronous function that will be used to load remote schemas when compileAsync
method is used and some reference is missing (option missingRefs
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 in Asynchronous compilation.
# 修改校验数据的选项
¥Options to modify validated data
# removeAdditional
Remove additional properties - see example in 删除附加属性。
¥Remove additional properties - see example in Removing additional properties.
如果使用 addMetaSchema
方法添加结构,则不使用此选项。
¥This option is not used if schema is added with addMetaSchema
method.
选项值:
¥Option values:
false
(default) - 不删除附加属性¥
false
(default) - not to remove additional properties"all"
- 所有附加属性都将被删除,无论结构中的additionalProperties
关键字如何(并且不会对它们进行校验)。¥
"all"
- all additional properties are removed, regardless ofadditionalProperties
keyword in schema (and no validation is made for them).true
- 仅删除additionalProperties
关键字等于false
的附加属性。¥
true
- only additional properties withadditionalProperties
keyword equal tofalse
are removed."failing"
- 结构校验失败的其他属性将被删除(其中additionalProperties
关键字是false
或结构)。¥
"failing"
- additional properties that fail schema validation will be removed (whereadditionalProperties
keyword isfalse
or schema).
# useDefaults
将丢失或未定义的属性和项目替换为相应 default
关键字中的值。默认行为是忽略 default
关键字。如果使用 addMetaSchema
方法添加结构,则不使用此选项。
¥Replace missing or undefined properties and items with the values from corresponding default
keywords. Default behaviour is to ignore default
keywords. This option is not used if schema is added with addMetaSchema
method.
参见 分配默认值 中的示例。
¥See examples in Assigning defaults.
选项值:
¥Option values:
false
(default) - do not use defaultstrue
- 按值插入默认值(使用对象字面量)。¥
true
- insert defaults by value (object literal is used)."empty"
- 除了缺失或未定义之外,还使用等于null
或""
(空字符串)的属性和项目的默认值。¥
"empty"
- in addition to missing or undefined, use defaults for properties and items that are equal tonull
or""
(an empty string).
# coerceTypes
更改数据的数据类型以匹配 type
关键字。请参阅 强制数据类型 和 强制规则 中的示例。
¥Change data type of data to match type
keyword. See the example in Coercing data types and coercion rules.
选项值:
¥Option values:
false
(default) - no type coercion.true
- 强制标量数据类型。¥
true
- coerce scalar data types."array"
- 除了标量类型之间的强制转换之外,还将标量数据强制转换为具有一个元素的数组,反之亦然(根据结构的要求)。¥
"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
添加 meta-schema (opens new window) 以便其他结构可以使用它(默认情况下为 true)。如果传递一个对象,它将用作没有 $schema
关键字的结构的默认元结构。这个默认的元结构必须有 $schema
关键字。
¥Add meta-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
根据元结构校验添加/编译的结构(默认为 true)。模式中的 $schema
属性可以是 http://json-schema.org/draft-07/schema (opens new window) 或不存在(将使用 Draft-07 元模式),也可以是对先前使用 addMetaSchema
方法添加的模式的引用。
¥Validate added/compiled schemas against meta-schema (true by default). $schema
property in the schema can be http://json-schema.org/draft-07/schema (opens new window) or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with addMetaSchema
method.
选项值:
¥Option values:
true
(default) - 如果校验失败,则抛出异常。¥
true
(default) - if the validation fails, throw the exception."log"
- 如果校验失败,则记录错误。¥
"log"
- if the validation fails, log error.false
- 跳过结构校验。¥
false
- skip schema validation.
# addUsedSchema
默认情况下,如果方法 compile
和 validate
具有不以 "" 开头的 $id
(或 id
)属性,则方法 compile
和 validate
会将结构添加到实例。如果 $id
存在且不唯一,则会抛出异常。将此选项设置为 false
可在使用这些方法时跳过向实例添加结构和 $id
唯一性检查。该选项不影响 addSchema
方法。
¥By default methods compile
and validate
add schemas to the instance if they have $id
(or id
) property that doesn't start with "#". If $id
is present and it is not unique the exception will be thrown. Set this option to false
to skip adding schemas to the instance and the $id
uniqueness check when these methods are used. This option does not affect addSchema
method.
# inlineRefs
影响引用结构的编译。
¥Affects compilation of referenced schemas.
选项值:
¥Option values:
true
(default) - 没有引用的引用模式是内联的,无论其大小如何 - it improves performance.¥
true
(default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - it improves performance.false
- 不是内联引用的结构(它们将始终被编译为单独的函数)。¥
false
- to not inline referenced schemas (they will always be compiled as separate functions).integer number - 限制将被内联的模式的关键字的最大数量(以平衡编译函数的总大小和性能)。
¥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
传递校验上下文来编译和校验关键字函数。如果此选项是 true
并且你使用 validate.call(context, data)
将一些上下文传递给已编译的校验函数,则 context
将在关键字中用作 this
。默认情况下,this
是 Ajv 实例。
¥Pass validation context to compile and validate keyword functions. If this option is true
and you pass some context to the compiled validation function with validate.call(context, data)
, the context
will be available as this
in your keywords. By default this
is Ajv instance.
# loopRequired
默认情况下,required
关键字被编译为单个表达式(或 allErrors
结构下的一系列语句),最多 200 个所需属性。传递整数以设置不同数量的属性,超过该数量的属性将在循环中校验 required
关键字(校验函数大小较小且性能较差)。
¥By default required
keyword is compiled into a single expression (or a sequence of statements in allErrors
mode) up to 200 required properties. Pass integer to set a different number of properties above which required
keyword will be validated in a loop (with a smaller validation function size and worse performance).
# loopEnum
v7默认情况下,enum
关键字被编译为单个表达式,最多可包含 200 个允许值。传递整数来设置值的数量,超过该值将在循环中校验 enum
关键字(校验函数大小较小且性能较差)。
¥By default enum
keyword is compiled into a single expression with up to 200 allowed values. Pass integer to set the number of values above which enum
keyword will be validated in a loop (with a smaller validation function size and worse performance).
# ownProperties
默认情况下,Ajv 迭代所有可枚举对象属性;当此选项为 true
时,仅迭代自己的可枚举对象属性(即直接在对象上而不是在其原型上找到)。由@mbroadst 贡献。
¥By default Ajv iterates over all enumerable object properties; when this option is true
only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst.
# multipleOfPrecision
默认情况下,通过将除法结果与该结果的 parseInt()
进行比较来校验 multipleOf
关键字的有效性。它适用于大于 1 的分隔符。对于诸如 0.01 之类的小除数,除法的结果通常不是整数(即使它应该是整数,请参阅问题 #84 (opens new window))。如果你需要使用小数除法器,请将此选项设置为某个正整数 N,以便使用以下公式校验 multipleOf
:Math.abs(Math.round(division) - division) < 1e-N
(速度较慢,但允许浮点算术偏差)。
¥By default multipleOf
keyword is validated by comparing the result of division with parseInt()
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 have multipleOf
validated using this formula: Math.abs(Math.round(division) - division) < 1e-N
(it is slower but allows for float arithmetic deviations).
# messages
在错误中包含人类可读的消息。默认为 true
。当消息在 Ajv 代码之外生成时(例如使用 ajv-i18n (opens new window)),可以传递 false
。
¥Include human-readable messages in errors. true
by default. false
can be passed when messages are generated outside of Ajv code (e.g. with ajv-i18n (opens new window)).
# uriResolver
默认情况下,uriResolver
未定义,并且依赖于嵌入式 uriResolver fast-uri (opens new window)。传递一个满足接口 UriResolver (opens new window) 的对象用于替换。一种替代方案是 uri-js (opens new window)。
¥By default uriResolver
is undefined and relies on the embedded uriResolver fast-uri (opens new window). Pass an object that satisfies the interface UriResolver (opens new window) to be used in replacement. One alternative is uri-js (opens new window).
# code
v7代码生成选项:
¥Code generation options:
type CodeOptions = {
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
}
type Source = {
code: string // unlike func.toString() it includes assignments external to function scope
scope: Scope // see Code generation (TODO)
}