5

I have an AJV schema like this:

// schema.js
module.exports = {
  title: 'task',
  description: 'A Task Schema',
  type: 'object',
  properties: {
    object_city: {
      title: 'City',
      type:'string'
    },
    object_zip: {
      title: 'Zip Code',
      type: 'string',
      maxLength: 5,
      minLength: 5
    }
  },
  required: ['object_zip', 'object_city'],
  additionalProperties: false
};

When I run my validation test against this schema, the result for missing object_city is:

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

But the result for a zip code being shorter than minLength is:

{ keyword: 'minLength',
  dataPath: '.object_zip',
  schemaPath: '#/properties/object_zip/minLength',
  params: { limit: 5 },
  message: 'should NOT be shorter than 5 characters' }

Please note the differences:

  • failed validation on required returns a blank dataPath, but failed validation on minLength returns '.object_zip' as dataPath
  • failed validation on required returns '#/required' as schemaPath and failed validation on minLength returns '#/properties/object_zip/minLength' as schemaPath

So here is my question: how can I get a consistent error handling?

LongHike
  • 4,016
  • 4
  • 37
  • 76
  • Same problem here. Maybe you should have filed this as an issue on their bugtracker. – jayarjo Nov 03 '18 at 19:35
  • 1
    I would have filed it, if had known whether it was a bug. But since at that time nobody seemed to have the same problem, I came to the conclusion that it was most likely my fault and not an AJV bug. So I chose to write my own validation and drop AJV. I try to be careful claiming something is a bug, because most of the time, it's a mistake on my behalf. – LongHike Nov 04 '18 at 14:35
  • The validation for `required` exists on the root schema `#/` i.e. when `object_zip` is missing, the root object is missing this property, and therefore it is considered to have failed the validation. On the other hand the validation for `minLength` exists on the sub schema `#/properties/object_zip` i.e. when the length falls short, the `object_zip` property is considered to have failed the validation. This is the correct behavior according to json-schema specification. If you want a different behavior, you should consider using a different library such as joi, that is not based on json-schema – aravindanve Jun 13 '20 at 10:32

0 Answers0