首页 > 解决方案 > 尽管有多个错误,但 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);
  }
该代码应该产生两个错误,因为 name 和 SKU 是必需的,但它只返回一个错误,请检查以下输出:

[ { keyword: 'required',
    dataPath: '',
    schemaPath: '#/required',
    params: { missingProperty: 'name' },
    message: 'should have required property \'name\'' } ]

标签: javascriptnode.jsecmascript-6ajv

解决方案


您需要为此设置配置。

如果您一次得到所有错误,那么您必须在创建 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


推荐阅读