You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
2.0 KiB
83 lines
2.0 KiB
12 months ago
|
// | ------------------------------------------------------------
|
||
|
// | @版本: version 0.1
|
||
|
// | @创建人: 【Nie-x7129】
|
||
|
// | @E-mail: x71291@outlook.com
|
||
|
// | @所在项目: initkoa
|
||
|
// | @文件描述: ajvTest.js -
|
||
|
// | @创建时间: 2023-11-25 21:59
|
||
|
// | @更新时间: 2023-11-25 21:59
|
||
|
// | @修改记录:
|
||
|
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||
|
// | =
|
||
|
// | ------------------------------------------------------------
|
||
|
const Ajv = require('ajv');
|
||
|
const ajv = new Ajv({ allErrors: true });
|
||
|
|
||
|
const schema = {
|
||
|
type: 'object',
|
||
|
properties: {
|
||
|
name: { type: 'string' },
|
||
|
age: { type: 'integer', minimum: 18 },
|
||
|
},
|
||
|
required: ['name', 'age'],
|
||
|
errorMessage: {
|
||
|
type: '数据应该是一个对象', // 整体 schema 错误消息
|
||
|
required: '对象缺少必要属性', // 缺少必要属性错误消息
|
||
|
properties: {
|
||
|
name: '姓名应该是一个字符串',
|
||
|
age: '年龄应该是一个大于或等于 18 的整数',
|
||
|
},
|
||
|
},
|
||
|
};
|
||
|
|
||
|
const validate = ajv.compile(schema);
|
||
|
|
||
|
const data = {
|
||
|
name: 123,
|
||
|
age: 17,
|
||
|
};
|
||
|
|
||
|
validate(data);
|
||
|
if (validate.errors) {
|
||
|
console.log(validate.errors); // 输出自定义错误消息
|
||
|
}
|
||
|
|
||
|
// ================================
|
||
|
|
||
|
const Ajv = require('ajv');
|
||
|
const ajv = new Ajv({ allErrors: true });
|
||
|
|
||
|
// 添加自定义关键字
|
||
|
ajv.addKeyword('isOldEnough', {
|
||
|
validate: function (schema, data) {
|
||
|
ajv.errors = [
|
||
|
{
|
||
|
keyword: 'isOldEnough',
|
||
|
message: '年龄必须大于18岁',
|
||
|
params: { keyword: 'isOldEnough' },
|
||
|
},
|
||
|
];
|
||
|
return data >= 18;
|
||
|
},
|
||
|
errors: true, // 使用自定义的错误列表
|
||
|
});
|
||
|
|
||
|
const schema = {
|
||
|
type: 'object',
|
||
|
properties: {
|
||
|
age: { type: 'integer', isOldEnough: true },
|
||
|
},
|
||
|
required: ['age'],
|
||
|
};
|
||
|
|
||
|
const validate = ajv.compile(schema);
|
||
|
|
||
|
const data = {
|
||
|
age: 17,
|
||
|
};
|
||
|
|
||
|
validate(data);
|
||
|
if (validate.errors) {
|
||
|
console.log(validate.errors); // 输出自定义错误消息
|
||
|
}
|