尽管存在多个

时间:2019-05-29 16:25:36

标签: javascript node.js ecmascript-6 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);
  }
该代码应产生两个错误,因为名称和SKU是必需的,但它仅返回一个错误,请检查以下输出:

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

1 个答案:

答案 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