使用AJV,可以通过使用'errorMessage”属性来创建自定义错误消息。下面是一个示例,演示如何使用AJV创建自定义错误消息:
const Ajv = require('ajv');
const ajv = new Ajv({ allErrors: true });
const schema = {
type: 'object',
properties: {
name: { type: 'string', errorMessage: { type: 'should be a string' } },
age: { type: 'number', errorMessage: { type: 'should be a number' } }
},
required: ['name', 'age']
};
const data = { name: 123, age: 'twenty' };
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) {
console.log(validate.errors);
}
在这个示例中,我们定义了一个Ajv实例,并传递一个标志将其配置为返回所有错误。然后,我们定义了一个包含两个属性的模式,其中每个属性都有一个自定义的错误消息。'validate”函数编译模式,并'data”传递给它进行验证。如果数据无效,则打印出错误消息。
上一篇:AJV类型脚本文件的独立验证代码
下一篇:ajv数组与联合类型