# API 参考
¥API Reference
- Ajv 构造函数和方法
- new Ajv(options: object)
- ajv.compile(schema: object):(data: any) => boolean | Promise < any >
- ajv.compileSerializer(schema: object):(data: any) => string
- ajv.compileParser(schema: object):(json: string) => any
- ajv.compileAsync(schema: object, meta?: boolean):Promise < Function >
- ajv.validate(schemaOrRef: object | string, data: any):布尔值
- ajv.addSchema(schema: object | object\[], key?: string):Ajv
- ajv.addMetaSchema(schema: object | object\[], key?: string):Ajv
- ajv.validateSchema(schema: object):布尔值
- ajv.getSchema(key: string):undefined | ((data: any) => boolean | Promise < any >)
- ajv.removeSchema(schemaOrRef: object | string | RegExp):Ajv
- ajv.addFormat(name: string, format: Format):Ajv
- ajv.addKeyword(definition: string | object):Ajv
- ajv.getKeyword(keyword: string):object | boolean
- ajv.removeKeyword(keyword: string):Ajv
- ajv.errorsText(errors?: object\[], options?: object):string
- 校验错误
# Ajv 构造函数和方法
¥Ajv constructor and methods
# new Ajv(options: object)
创建 Ajv 实例:
¥Create Ajv instance:
const ajv = new Ajv()
见 选项
¥See Options
# ajv.compile(schema: object):(data: any) => boolean | Promise < any >
生成校验函数并缓存编译后的结构以供将来使用。
¥Generate validating function and cache the compiled schema for future use.
校验函数返回一个布尔值(或 promise 必须具有 $async: true
属性的异步模式 - 请参阅 异步校验)。该函数具有属性 errors
和 schema
。上次校验期间遇到的错误将分配给 errors
属性(如果没有错误,则分配给 null
)。schema
属性包含对原始结构的引用。
¥Validating function returns a boolean value (or promise for async schemas that must have $async: true
property - see Asynchronous validation). This function has properties errors
and schema
. Errors encountered during the last validation are assigned to errors
property (it is assigned null
if there was no errors). schema
property contains the reference to the original schema.
除非 validateSchema
选项为 false,否则传递给此方法的结构将根据元结构进行校验。如果结构无效,则会抛出错误。参见 options。
¥The schema passed to this method will be validated against meta-schema unless validateSchema
option is false. If schema is invalid, an error will be thrown. See options.
在 TypeScript 中,如果传递类型参数,返回的校验函数可以是类型保护:
¥In typescript returned validation function can be a type guard if you pass type parameter:
interface Foo {
foo: number
}
const FooSchema: JSONSchemaType<Foo> = {
type: "object",
properties: {foo: {type: "number"}},
required: ["foo"],
additionalProperties: false,
}
const validate = ajv.compile<Foo>(FooSchema) // type of validate extends `(data: any) => data is Foo`
const data: any = {foo: 1}
if (validate(data)) {
// data is Foo here
console.log(data.foo)
} else {
console.log(validate.errors)
}
请参阅 考试 (opens new window) 中的更高级示例。
¥See more advanced example in the test (opens new window).
# ajv.compileSerializer(schema: object):(data: any) => string
NEW基于 JTD 结构 生成序列化函数(缓存模式) - 仅在 Ajv 的 JTD 实例中(参见下面的示例)。
¥Generate serializing function based on the JTD schema (caches the schema) - only in JTD instance of Ajv (see example below).
从 JTD 结构编译的序列化器比使用 JSON.stringify
编译的序列化器快 10 倍以上,因为它们不会遍历所有数据,仅遍历结构中定义的属性。
¥Serializers compiled from JTD schemas can be more than 10 times faster than using JSON.stringify
, because they do not traverse all the data, only the properties that are defined in the schema.
结构中未定义的属性不会包含在序列化 JSON 中,除非结构具有 additionalProperties: true
标志。从应用安全的角度来看,它也可能是有益的,因为它可以防止泄漏意外/临时添加到 API 响应的附加属性。
¥Properties not defined in the schema will not be included in serialized JSON, unless the schema has additionalProperties: true
flag. It can also be beneficial from the application security point of view, as it prevents leaking accidentally/temporarily added additional properties to the API responses.
如果将 JTD 与 typescript 一起使用,则结构的类型可以从数据类型派生,并且生成的序列化程序在这种情况下仅接受正确的数据类型:
¥If you use JTD with typescript, the type for the schema can be derived from the data type, and generated serializer would only accept correct data type in this case:
import Ajv, {JTDSchemaType} from "ajv/dist/jtd"
const ajv = new Ajv()
interface MyData {
foo: number
bar?: string
}
const mySchema: JTDSchemaType<MyData> = {
properties: {
foo: {type: "int32"} // any JTD number type would be accepted here
},
optionalProperties: {
bar: {type: "string"}
}
}
const serializeMyData = ajv.compileSerializer(mySchema)
// serializeMyData has type (x: MyData) => string
// it prevents you from accidentally passing the wrong type
编译的序列化器不校验数据!
假设根据结构数据是有效的。
¥It is assumed that the data is valid according to the schema.
# ajv.compileParser(schema: object):(json: string) => any
NEW基于 JTD 结构 生成解析函数(缓存 schema) - 仅在 Ajv 的 JTD 实例中(参见下面的示例)。
¥Generate parsing function based on the JTD schema (caches the schema) - only in JTD instance of Ajv (see example below).
如果 JSON 字符串根据模式有效,从 JTD 模式编译的解析器具有与 JSON.parse
* 相当的性能(并且它们不只是解析 JSON - 它们确保解析的 JSON 根据模式有效,因为它们 parse),但如果字符串无效,它们可以快很多倍 - 例如,如果模式需要一个对象,并且 JSON 字符串是数组,则解析器将在第一个字符处失败。
¥Parsers compiled from JTD schemas have comparable performance to JSON.parse
* in case JSON string is valid according to the schema (and they do not just parse JSON - they ensure that parsed JSON is valid according to the schema as they parse), but they can be many times faster in case the string is invalid - for example, if schema expects an object, and JSON string is array the parser would fail on the first character.
如果结构中未定义属性,则解析将失败,除非结构具有 additionalProperties: true
标志。
¥Parsing will fail if there are properties not defined in the schema, unless the schema has additionalProperties: true
flag.
如果你将 JTD 与 typescript 一起使用,则结构的类型可以从数据类型派生,并且生成的解析器将返回正确的数据类型(请参阅 serialize 部分中的定义示例):
¥If you use JTD with typescript, the type for the schema can be derived from the data type, and generated parser will return correct data type (see definitions example in the serialize section):
const parseMyData = ajv.compileParser(mySchema)
// parseMyData has type (s: string) => MyData | undefined
// it returns correct data type in case parsing is successful and undefined if not
const validData = parseMyData('{"foo":1}') // {foo: 1} - success
const invalidData = parseMyData('{"x":1}') // undefined - failure
console.log(parseMyData.position) // 4
console.log(parseMyData.message) // property x not allowed
* 只要不使用空模式 {}
- 在这种情况下有可能提高性能。此外,解析 discriminator
模式的性能取决于模式中鉴别器标签的位置 - 如果标签是第一个属性,将获得最佳解析性能 - 这就是编译的 JTD 序列化器在鉴别器模式的情况下生成 JSON 的方式。
¥* As long as empty schema {}
is not used - there is a possibility to improve performance in this case. Also, the performance of parsing discriminator
schemas depends on the position of discriminator tag in the schema - the best parsing performance will be achieved if the tag is the first property - this is how compiled JTD serializers generate JSON in case of discriminator schemas.
# ajv.compileAsync(schema: object, meta?: boolean):Promise < Function >
compile
方法的异步版本,使用 options.loadSchema
中的异步函数加载缺失的远程结构。该函数返回一个解析为校验函数的 Promise。将使用 2 个参数调用传递给 compileAsync
的可选回调:错误(或 null)和校验函数。在以下情况下,返回的 Promise 将被拒绝(并且回调将被调用并出现错误):
¥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:
无法加载缺少的结构(
loadSchema
返回拒绝的 Promise)。¥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.
你可以通过传递 true
作为第二个参数来异步编译元结构。
¥You can asynchronously compile meta-schema by passing true
as the second parameter.
与 compile
类似,它可以在 TypeScript 中返回类型保护。
¥Similarly to compile
, it can return type guard in typescript.
参见 异步结构加载 中的示例。
¥See example in Asynchronous schema loading.
# ajv.validate(schemaOrRef: object | string, data: any):布尔值
¥ajv.validate(schemaOrRef: object | string, data: any): boolean
使用传递的结构校验数据(它将被编译和缓存)。
¥Validate data using passed schema (it will be compiled and cached).
你可以使用之前传递给 addSchema
的密钥、结构 ID(如果存在于结构或任何之前解析的引用中)来代替结构。
¥Instead of the schema you can use the key that was previously passed to addSchema
, the schema id if it was present in the schema or any previously resolved reference.
校验错误将在 Ajv 实例的 errors
属性中可用(如果没有错误,则为 null
)。
¥Validation errors will be available in the errors
property of Ajv instance (null
if there were no errors).
在 TypeScript 中,此方法可以充当类型保护(类似于 compile
方法返回的函数 - 请参阅此处的示例)。
¥In typescript this method can act as a type guard (similarly to function returned by compile
method - see example there).
保存错误属性
每次调用此方法时,错误都会被覆盖,因此如果以后想使用它们,则需要将它们复制到另一个变量。
¥Every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later.
如果结构是异步的(顶层有 $async
关键字),则此方法返回 Promise。参见 异步校验。
¥If the schema is asynchronous (has $async
keyword on the top level) this method returns a Promise. See Asynchronous validation.
# ajv.addSchema(schema: object | object[], key?: string):Ajv
将架构添加到校验器实例。此方法不编译结构(但仍然校验它们)。因此,可以按任意顺序添加依赖,并且支持循环依赖。它还可以防止对作为其他结构的容器但不作为整体使用的结构进行不必要的编译。
¥Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole.
可以传递结构数组(结构应该有 ids),第二个参数将被忽略。
¥Array of schemas can be passed (schemas should have ids), the second parameter will be ignored.
可以传递可用于引用结构的密钥,如果结构内没有 id,则将用作结构 id。如果未传递密钥,则结构 id 将用作密钥。
¥Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key.
添加结构后,它(以及其中的所有引用)可以在其他结构中引用并用于校验数据。
¥Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data.
虽然 addSchema
不编译模式,但不需要显式编译 - 第一次使用模式时将对其进行编译。
¥Although addSchema
does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time.
默认情况下,在添加结构之前会根据元结构对其进行校验,如果结构未通过校验,则会引发异常。此行为由 validateSchema
选项控制。
¥By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by validateSchema
option.
方法链接
Ajv 返回其实例以从所有前缀为 add*
和 remove*
的方法进行链接:
¥Ajv returns its instance for chaining from all methods prefixed add*
and remove*
:
const validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri)
# ajv.addMetaSchema(schema: object | object[], key?: string):Ajv
添加可用于校验其他模式的元模式。应该使用该函数而不是 addSchema
,因为可能存在会错误编译元结构的实例选项(目前是 removeAdditional
选项)。
¥Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of addSchema
because there may be instance options that would compile a meta schema incorrectly (at the moment it is removeAdditional
option).
无需显式添加 Draft-07 元架构 (http://json-schema.org/draft-07/schema (opens new window)) - 它是默认添加的,除非选项 meta
设置为 false
。仅当你想要使用更改后的元结构来校验结构时,才需要使用它。参见 validateSchema
。
¥There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema (opens new window)) - it is added by default, unless option meta
is set to false
. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See validateSchema
.
# ajv.validateSchema(schema: object):布尔值
¥ajv.validateSchema(schema: object): boolean
校验结构。由于 JSON Schema 标准中的 uri
格式不一致,因此应该使用此方法来校验 schema,而不是 validate
。
¥Validates schema. This method should be used to validate schemas rather than validate
due to the inconsistency of uri
format in JSON Schema standard.
默认情况下,添加结构时会自动调用此方法,因此你很少需要直接使用它。
¥By default this method is called automatically when the schema is added, so you rarely need to use it directly.
如果结构没有 $schema
属性,则会根据草案 6 元结构对其进行校验(选项 meta
不应为 false)。
¥If schema doesn't have $schema
property, it is validated against draft 6 meta-schema (option meta
should not be false).
如果结构具有 $schema
属性,则具有此 id 的结构(应事先添加)用于校验传递的结构。
¥If schema has $schema
property, then the schema with this id (that should be previously added) is used to validate passed schema.
错误将在 ajv.errors
处出现。
¥Errors will be available at ajv.errors
.
# ajv.getSchema(key: string):undefined | ((data: any) => boolean | Promise < any >)
通过传递给 addSchema
的密钥或其完整引用 (id) 检索先前使用 addSchema
添加的编译结构。返回的校验函数具有 schema
属性以及对原始结构的引用。
¥Retrieve compiled schema previously added with addSchema
by the key passed to addSchema
or by its full reference (id). The returned validating function has schema
property with the reference to the original schema.
# ajv.removeSchema(schemaOrRef: object | string | RegExp):Ajv
删除添加/缓存的结构。即使结构被其他结构引用,也可以安全地删除它,因为依赖结构具有本地引用。
¥Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references.
可以使用以下方法删除结构:
¥Schema can be removed using:
密钥已传递至
addSchema
¥key passed to
addSchema
这是完整的参考(id)
¥it's full reference (id)
应匹配结构 ID 或键的正则表达式(元结构不会被删除)
¥RegExp that should match schema id or key (meta-schemas won't be removed)
实际的结构对象(可以选择序列化)以从缓存中删除结构
¥actual schema object (that will be optionally serialized) to remove schema from cache
如果没有传递参数,则除元结构外的所有结构都将被删除,并且缓存将被清除。
¥If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared.
# ajv.addFormat(name: string, format: Format):Ajv
type Format =
| true // to ignore this format (and pass validation)
| string // will be converted to RegExp
| RegExp
| (data: string) => boolean
| Object // format definition (see below and in types)
添加格式以校验字符串或数字。
¥Add format to validate strings or numbers.
如果传递对象,它应该具有属性 validate
、compare
和 async
:
¥If object is passed it should have properties validate
, compare
and async
:
interface FormatDefinition { // actual type definition is more precise - see types.ts
validate: string | RegExp | (data: number | string) => boolean | Promise<boolean>
compare: (data1: string, data2: string): number // an optional function that accepts two strings
// and compares them according to the format meaning.
// This function is used with keywords `formatMaximum`/`formatMinimum`
// (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package).
// It should return `1` if the first value is bigger than the second value,
// `-1` if it is smaller and `0` if it is equal.
async?: true // if `validate` is an asynchronous function
type?: "string" | "number" // "string" is default. If data type is different, the validation will pass.
}
还可以通过 formats
选项添加格式。
¥Formats can be also added via formats
option.
# ajv.addKeyword(definition: string | object):Ajv
将校验关键字添加到 Ajv 实例。
¥Add validation keyword to Ajv instance.
关键字应不同于所有标准 JSON 结构关键字,并且不同于先前定义的关键字。无法重新定义关键字或从实例中删除关键字定义。
¥Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance.
关键字必须以 ASCII 字母 _
或 $
开头,并且可以以 ASCII 字母、数字、_
、$
、-
或 :
继续。建议对关键字使用特定于应用的前缀,以避免当前和将来的名称冲突。
¥Keyword must start with an ASCII letter, _
or $
, and may continue with ASCII letters, numbers, _
, $
, -
, or :
.
It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions.
关键词示例:
¥Example Keywords:
"xyz-example"
:有效,并使用 xyz 项目的前缀以避免名称冲突。¥
"xyz-example"
: valid, and uses prefix for the xyz project to avoid name collisions."example"
:有效,但不推荐,因为它可能与未来版本的 JSON Schema 等发生冲突。¥
"example"
: valid, but not recommended as it may collide with future versions of JSON Schema etc."3-example"
:无效,因为数字不允许作为关键字中的第一个字符¥
"3-example"
: invalid as numbers are not allowed to be the first character in a keyword
关键字定义是一个具有以下属性的对象:
¥Keyword definition is an object with the following properties:
interface KeywordDefinition {
// actual type definition is more precise - see types.ts
keyword: string // keyword name
type?: string | string[] // JSON data type(s) the keyword applies to. Default - all types.
schemaType?: string | string[] // the required schema JSON type
code?: Function // function to generate code, used for all pre-defined keywords
validate?: Function // validating function
compile?: Function // compiling function
macro?: Function // macro function
error?: object // error definition object - see types.ts
schema?: false // used with "validate" keyword to not pass schema to function
metaSchema?: object // meta-schema for keyword schema
dependencies?: string[] // properties that must be present in the parent schema -
// it will be checked during schema compilation
implements?: string[] // keyword names to reserve that this keyword implements
modifying?: true // MUST be passed if keyword modifies data
valid?: boolean // to pre-define validation result, validation function result will be ignored -
// this option MUST NOT be used with `macro` keywords.
$data?: true // to support [\$data reference](./guide/combining-schemas.md#data-reference) as the value of keyword.
// The reference will be resolved at validation time. If the keyword has meta-schema,
// it would be extended to allow $data and it will be used to validate the resolved value.
// Supporting $data reference requires that keyword has `code` or `validate` function
// (the latter can be used in addition to `compile` or `macro`).
$dataError?: object // error definition object for invalid \$data schema - see types.ts
async?: true // if the validation function is asynchronous
// (whether it is returned from `compile` or passed in `validate` property).
// It should return a promise that resolves with a value `true` or `false`.
// This option is ignored in case of "macro" and "code" keywords.
errors?: boolean | "full" // whether keyword returns errors.
// If this property is not passed Ajv will determine
// if the errors were set in case of failed validation.
}
如果定义对象中仅提供属性 keyword
,你还可以传递关键字名称作为参数。
¥If only the property keyword
is provided in the definition object, you can also pass the keyword name as the argument.
compile
、macro
和 code
是互斥的,一次只能使用一个。validate
可以单独使用,也可以与 compile
或 macro
一起使用以支持 $data 参考。
¥compile
, macro
and code
are mutually exclusive, only one should be used at a time. validate
can be used separately or in addition to compile
or macro
to support $data reference.
仅针对适用的数据类型校验关键字
如果关键字校验的数据类型与其定义中的类型不同,则不会调用校验函数(并且不会使用扩展宏),因此无需在校验函数内检查数据类型 或由宏函数返回的内部模式(除非你想强制执行特定类型并且由于某种原因不想为此使用单独的 type
关键字)。与标准关键字的工作方式相同,如果关键字不适用于正在校验的数据类型,则该关键字的校验将成功。
¥If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate type
keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed.
详细信息请参见 用户定义的关键字。
¥See User defined keywords for more details.
# ajv.getKeyword(keyword: string):object | boolean
返回关键字定义,如果关键字未知,则返回 false
。
¥Returns keyword definition, false
if the keyword is unknown.
# ajv.removeKeyword(keyword: string):Ajv
删除添加或预定义的关键字,以便你可以重新定义它们。
¥Removes added or pre-defined keyword so you can redefine them.
虽然此方法可用于扩展预定义关键字,但也可用于完全改变其含义 - 这可能会导致意想不到的结果。
¥While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results.
编译结构并删除关键字
删除关键字之前编译的结构将继续工作,无需更改。要重新编译结构,请使用 removeSchema
方法并再次编译它们。
¥The schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use removeSchema
method and compile them again.
# ajv.errorsText(errors?: object[], options?: object):string
返回字符串中包含所有错误的文本。
¥Returns the text with all errors in a String.
选项可以具有属性 separator
(用于分隔错误的字符串,默认为 ",")和 dataVar
(instancePath 前缀的变量名称,默认为 "data")。
¥Options can have properties separator
(string used to separate errors, ", " by default) and dataVar
(the variable name that instancePath is prefixed with, "data" by default).
# 校验错误
¥Validation errors
如果校验失败,Ajv 会将错误数组分配给校验函数的 errors
属性(或者当调用 validate
或 validateSchema
方法时分配给 Ajv 实例的 errors
属性)。在 异步校验 的情况下,返回的 Promise 被拒绝,异常 Ajv.ValidationError
具有 errors
属性。
¥In case of validation failure, Ajv assigns the array of errors to errors
property of validation function (or to errors
property of Ajv instance when validate
or validateSchema
methods were called). In case of asynchronous validation, the returned promise is rejected with exception Ajv.ValidationError
that has errors
property.
# 错误对象
¥Error objects
每个报告的错误都是一个具有以下属性的对象:
¥Each reported error is an object with the following properties:
interface ErrorObject {
keyword: string // validation keyword.
instancePath: string // JSON Pointer to the location in the data instance (e.g., `"/prop/1/subProp"`).
schemaPath: string // JSON Pointer to the location of the failing keyword in the schema
params: object // type is defined by keyword value, see below
// params property is the object with the additional information about error
// it can be used to generate error messages
// (e.g., using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package).
// See below for parameters set by all keywords.
propertyName?: string // set for errors in `propertyNames` keyword schema.
// `instancePath` still points to the object in this case.
message?: string // the error message (can be excluded with option `messages: false`).
// Options below are added with `verbose` option:
schema?: any // the value of the failing keyword in the schema.
parentSchema?: object // the schema containing the keyword.
data?: any // the data validated by the keyword.
}
对于 JTD 模式,instancePath
和 schemaPath
取决于故障的性质 - 错误与 RFC8927 (opens new window) 一致。
¥For JTD schemas instancePath
and schemaPath
depend on the nature of the failure - the errors are consistent with RFC8927 (opens new window).
# 错误参数
¥Error parameters
错误中 params
对象的属性取决于校验失败的关键字。
¥Properties of params
object in errors depend on the keyword that failed validation.
在 TypeScript 中,ErrorObject 是一个可区分的联合,它允许根据关键字的值确定错误参数的类型:
¥In typescript, the ErrorObject is a discriminated union that allows to determine the type of error parameters based on the value of keyword:
const ajv = new Ajv()
const validate = ajv.compile<MyData>(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
// ...
}
}
}
另请参阅 这次测试 (opens new window) 中的示例
¥Also see an example in this test (opens new window)
maxItems
、minItems
、maxLength
、minLength
、maxProperties
、minProperties
:
type ErrorParams = {limit: number} // keyword value
additionalItems
:
// when `items` is an array of schemas and `additionalItems` is false:
type ErrorParams = {limit: number} // the maximum number of allowed items
additionalProperties
:
type ErrorParams = {additionalProperty: string}
// the property not defined in `properties` and `patternProperties` keywords
dependencies
:
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
}
format
:
type ErrorParams = {format: string} // keyword value
maximum
、minimum
、exclusiveMaximum
、exclusiveMinimum
:
type ErrorParams = {
limit: number // keyword value
comparison: "<=" | ">=" | "<" | ">" // operation to compare the data to the limit,
// with data on the left and the limit on the right
}
multipleOf
:
type ErrorParams = {multipleOf: number} // keyword value
pattern
:
type ErrorParams = {pattern: string} // keyword value
required
:
type ErrorParams = {missingProperty: string} // required property that is missing
propertyNames
:
type ErrorParams = {propertyName: string} // invalid property name
用户定义的关键字可以定义其他关键字参数。
¥User-defined keywords can define other keyword parameters.
# 国际化错误
¥Errors i18n
你可以使用 ajv-i18n (opens new window) 包来生成其他语言的错误。
¥You can use ajv-i18n (opens new window) package to generate errors in other languages.
# 错误记录
¥Error logging
日志器实例可以通过 logger
选项传递给 Ajv 构造函数。只要包或其关联的封装器公开所需的方法,就支持使用其他日志记录包。如果缺少任何必需的方法,则会抛出异常。
¥A logger instance can be passed via logger
option to Ajv constructor. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown.
- Required Methods:
log
、warn
、error
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)
},
},
})
# 选项
¥Options
本栏目移至 初始化选项 页
¥This section is moved to Initialization options page