javascript - 尽管有多个错误,但 AJV 只返回一个错误
问题描述
我正在尝试将 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\'' } ]
解决方案
您需要为此设置配置。
如果您一次得到所有错误,那么您必须在创建 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
推荐阅读
- excel - 通过 VBA 设置默认打印机
- c# - 将控制器 ASP.NET 中的 JSON 哈希集反序列化为哈希集或字典
- apache-kafka-streams - 2.3.1版本删除空目录失败
- javascript - 如果等于当前 URL,则 Jquery 添加 Active 类
- java - 有没有更好的方法让我的计算机对手生成(3>随机长度<=7)的单词?
- azure - 从 Azure 部署中排除 Azure Function 中的文件
- java - 可缓存如何通过使用其名称来获取方法参数值
- php - Wordpress PHP.INI 噩梦
- c# - 覆盖泛型基类型的方法
- pytorch - 如何在pytorch中批处理对话数据集?