我查了官方文档,可以这样写
const Ajv = require('ajv').default
const addFormats = require('ajv-formats')
const schema = {
type: 'object',
properties: {
name: {
type: 'string',
format: 'email',
// minLength: 2,
},
age: {
type: 'number',
},
pets: {
type: 'array',
},
isWorker: {
type: 'boolean',
},
},
required: ['name', 'age'],
}
const data = {
name: 'sam@163.com',
age: 18,
pets: ['mama', 'mimi'],
isWorker: true,
}
const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}
addFormats(ajv, ['email']) // list 为要在schema的json串中使用的keyword,用什么就写什么,这里之用到email就写email
const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) console.log(validate.errors)