Ajv JSON schema validator-format

387 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情

JSON Schema 内置format类型

  1. Json Schema String类型,format内置的校验类型。
内置格式类型说明格式
'data-time'日期和时间2018-11-13T20:20:39+00:00
time时间20:20:39+00:00
date日期2018-11-13
emailInternet 电子邮件地址-
hostname主机-
ipv4IPv4-
ipv6IPv6-

PS: 这里没一一列举所有的类型,具体的可以到 Understanding JSON Schema 了解。

JSON Schema定义的格式

Ajv format的应用和扩展

应用

从版本 7 开始,Ajv 不包括 JSON Schema 规范定义的格式 - 这些和其他几种格式由ajv-formats提供 (打开新窗口)插入。

 const Ajv = require("ajv")
 const addFormats = require("ajv-formats")
 ​
 const ajv = new Ajv()
 addFormats(ajv)

以下格式在ajv-formats中定义 (打开新窗口)使用“格式”关键字进行字符串验证:

扩展

使用addFormat方法添加和替换任何格式:

 ajv.addFormat("identifier", /^a-z$_[a-zA-Z$_0-9]*$/)

Ajv 还允许定义仅适用于数字的格式:

 ajv.addFormat("byte", {
   type: "number",
   validate: (x) => x >= 0 && x <= 255 && x % 1 == 0,
 })

自定义自己的格式导入:

 const {default: Ajv, _} = require("ajv")
 const ajv = new Ajv({code: {formats: _`require("./my_formats")`}})

addFormat添加格式要求

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)

如果传递了Object属性,它还应有一下属性:

 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.
 }

ajv-formats插件库源码

ajv-formats插件库,做内置类型的维护,和实现。通过addFormats方法,添加到ajv中,实现JSON Schema的校验。

定义的类型:

"date","time","date-time","iso-time","iso-date-time","duration","uri","uri-reference","uri-template","url","email","hostname","ipv4","ipv6","regex","uuid","json-pointer","json-pointer-uri-fragment","relative-json-291pxpointer","byte","int32","int64","float","double","password","binary",

类型实现: image.png


image.png

在线运行

ajv在线运行

 const Ajv = require("ajv")
 const addFormats = require("ajv-formats")
  
 const ajv = new Ajv()
 addFormats(ajv)
  
 const schema = {
   type: "string",
   format: 'email'
 };
  
  
 const validate = ajv.compile(schema)
  
 const data = '123123@qq.com'
  
 const valid = validate(data)
 console.log(valid)
 if (!valid) console.log(validate.errors)

结果

image.png

总结

  1. Ajv通过ajv-formats插件库维护format类型
  2. Ajv通过addFormat,添加自定义规则

参考文章

ajv 格式存储库