https://github.com/ajv-validator/ajv-formats
Ajv formats类型 https://ajv.js.org/options.html#formats
formats只校验字符串和数字类型的数据,其他类型是无效的
- string
- number
// es6 require
import Ajv from "ajv"
import addFormats from "ajv-formats"
// Node.js require
const Ajv = require("ajv")
const addFormats = require("ajv-formats")
const ajv = new Ajv()
addFormats(ajv)
formats
ajv.addFormat 添加校验规则
https://ajv.js.org/api.html#ajv-addformat-name-string-format-format-ajv
// ajv.addFormat(name: string, format: Format)
import Ajv from "ajv"
const ajv = new Ajv();
ajv.addFormat('validateUserName', data => {
console.log('data', data);
return data === 'lucy'
})
// 使用自定义的 format
const schema = {
type: 'object',
properties: {
name: {
type: 'string',
format: 'validateUserName'
},
age: {
type: 'number'
},
pets: {
type: 'array',
items: [
{type: 'string'}, {type: 'number'}
]
}
},
required: ['name', 'age']
}
const validate = ajv.compile(schema);
const valid = validate({
name: 'lucy',
age: 18,
})