小知识,大挑战!本文正在参与“程序员必备小知识”创作活动
Ajv 转换错误语言_自定义关键字: 如何自定义错误信息
设置 Ajv 标准关键字错误提示 语言包
// ajv_lang_demo.js
const Ajv = require('ajv')
const localize = require('ajv-i18n') // ++++
const addFormats = require('ajv-formats')
const schema = {
type: 'object',
properties: {
name: {
type: 'string',
minLength: 10
}
},
required: ['name']
}
const data = {
name: 'kiky',
}
const ajv = new Ajv()
addFormats(ajv) // 添加自定义 format
const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) {
localize.zh(validate.errors) // 设置Ajv标准关键字错误提示返回的message语言为中文
console.log(validate.errors)
}
$ node ajv_lang_demo.js
[
{
instancePath: '/name',
schemaPath: '#/properties/name/minLength',
keyword: 'minLength',
params: { limit: 10 },
message: '不应少于 10 个字符'
}
]
自定义关键字返回的错误信息
// Node.js require:
const Ajv = require('ajv')
const localize = require('ajv-i18n')
const addFormats = require('ajv-formats')
const schema = {
type: 'object',
properties: {
name: {
type: 'string',
minLength: 3,
test: true
},
age: {
type: 'number'
},
pets: {
type: 'array',
minItems: 2,
maxItems: 2,
items: [
{ type: 'string' },
{ type: 'number' }
]
},
isWorker: {
type: 'boolean'
},
email: {
type: 'string',
format: 'email'
}
},
required: ['name']
}
const data = {
name: 'kiky'
}
const ajv = new Ajv()
addFormats(ajv) // 添加自定义 format
// ++++ 添加自定义关键字, 自定义返回的错误信息
ajv.addKeyword('test', {
validate: function fun(schema, data) {
fun.errors = [{
keyword: 'test',
dataPath: '.name',
schemaPath: '#/properties/name/test',
params: { keyword: 'test' },
message: 'Hello world'
}]
return false
}
})
const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) {
// localize.zh(validate.errors)
console.log(validate.errors)
}
自定义错误信息
$ yarn add ajv-errors
// Node.js require:
const Ajv = require('ajv')
const localize = require('ajv-i18n')
const addFormats = require('ajv-formats')
const schema = {
type: 'object',
properties: {
name: {
type: 'string',
minLength: 3,
test: true,
errorMessage: {
type: '必须是字符串',
minLength: '长度不能小于3',
test: 'test规则校验失败'
}
},
age: {
type: 'number'
},
pets: {
type: 'array',
minItems: 2,
maxItems: 2,
items: [
{ type: 'string' },
{ type: 'number' }
]
},
isWorker: {
type: 'boolean'
},
email: {
type: 'string',
format: 'email'
}
},
required: ['name']
}
const data = {
name: 'kiky'
}
const ajv = new Ajv({ allErrors: true })
require('ajv-errors')(ajv)
addFormats(ajv) // 添加自定义 format
ajv.addKeyword('test', {
macro() {
return {
minLength: 10
}
}
})
const validate = ajv.compile(schema)
const valid = validate(data)
console.log('valid:', valid)
if (!valid) {
// localize.zh(validate.errors)
console.log(validate.errors)
}