Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJV return only one error although there is multiple

I'm trying to use AJV with the below code, when I validate an object with multiple errors, AJV throws only one error at a time.

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);
  }
That code should produce two errors, as name and SKU is required, but it returns only one error, check the below output:

[ { keyword: 'required',
    dataPath: '',
    schemaPath: '#/required',
    params: { missingProperty: 'name' },
    message: 'should have required property \'name\'' } ]
like image 423
Elbassel Avatar asked May 29 '19 16:05

Elbassel


1 Answers

You need to set the configuration for that.

If you have get all the errors in once then you have to set this object param when creating an object of ajv {allErrors: true}

here is updated the code.

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);
}

Please also check this link for more configuration params. Link https://github.com/epoberezkin/ajv#options

like image 104
Chintan Kotadiya Avatar answered Sep 28 '22 08:09

Chintan Kotadiya