【问题标题】:AJV return only one error although there is multiple尽管有多个错误,但 AJV 只返回一个错误
【发布时间】:2019-10-15 07:43:18
【问题描述】:

我正在尝试将 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\'' } ]

【问题讨论】:

    标签: javascript node.js ecmascript-6 ajv


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多