我正在尝试将AJV与以下代码结合使用,当我验证一个具有多个错误的对象时,AJV一次仅抛出一个错误。
const schema = {
type: 'object',
properties: {
name: {type: 'string', minLength: 1, maxLength: 1},
sku: { type: 'string', minLength: 1, maxLength: 200},
},
required: ['name', 'sku']
}
const ajv = require('ajv');
const validator = new ajv();
const valid = validator.validate(schema, {});
if (!valid) {
console.log(validator.errors);
}
[ { keyword: 'required',
dataPath: '',
schemaPath: '#/required',
params: { missingProperty: 'name' },
message: 'should have required property \'name\'' } ]
答案 0 :(得分:1)
您需要为此设置配置。
如果一次遇到所有错误,则在创建ajv {allErrors: true}
的对象时必须设置此对象参数
此处更新了代码。
const schema = {
type: 'object',
properties: {
name: {type: 'string', minLength: 1, maxLength: 1},
sku: { type: 'string', minLength: 1, maxLength: 200},
},
required: ['name', 'sku']
}
const ajv = require('ajv');
const validator = new ajv({allErrors:true});
const valid = validator.validate(schema, {});
if (!valid) {
console.log(validator.errors);
}
也请检查此链接以获取更多配置参数。链接https://github.com/epoberezkin/ajv#options