在学习Vue3.0+TS打造企业级组件库 前端中高级开发者必修课这个教程的时候,很多人如果跟着教程走,学到3-3 json-schema的format和自定义format这个章节的时候,会发现你如果跟着教程添加format,然后声明format为email类型
const Ajv = require('ajv')
const addFormats = require('ajv-formats')
const ajv = new Ajv()
addFormats(ajv)
const schema = {
type: 'object',
properties: {
name: {
type: 'string',
format: 'email'
// minLength:10,
},
age: {
type: 'number',
},
pets: {
type: 'array',
items: [
{
type: 'string',
}, {
type: 'number'
}
],
},
isWorker: {
type: 'boolean',
},
},
required: ['name', 'age'],
}
// const ajv = new Ajv()
const validate = ajv.compile(schema)
const valid = validate({
name: 'webshi',
age: 18,
pets: ['nihoa', 12],
isWorker: true,
})
if (!valid) console.log(validate.errors)
运行后会出现这个错误:
Error: unknown format “email” ignored in schema at path "#/properties/name"
按照视频教程,由于你输入的格式不是邮箱的格式应该运行后的提示应该是这样的
可是你按照教程的步骤走出现的问题是
Error: unknown format “email” ignored in schema at path "#/properties/name"
出现这个问题的原因是你如果想在当前的文件下使用format你就要把format引入进来,你如果不引入就使用这个方法,文件是无法找到这个方法的,就会报这个错误。
解决方法是在使用这个方法的文件下,引入format。
const Ajv = require('ajv')
const addFormats = require('ajv-formats')
const ajv = new Ajv()
addFormats(ajv)
完整代码:
const Ajv = require('ajv')
const addFormats = require('ajv-formats')
const ajv = new Ajv()
addFormats(ajv)
const schema = {
type: 'object',
properties: {
name: {
type: 'string',
format: 'email'
// minLength:10,
},
age: {
type: 'number',
},
pets: {
type: 'array',
items: [
{
type: 'string',
}, {
type: 'number'
}
],
},
isWorker: {
type: 'boolean',
},
},
required: ['name', 'age'],
}
// const ajv = new Ajv()
const validate = ajv.compile(schema)
const valid = validate({
name: 'webshi',
age: 18,
pets: ['nihoa', 12],
isWorker: true,
})
if (!valid) console.log(validate.errors)
运行后的结果就跟视频教程上是一样的了