Search code examples
undefinedjsonschemajson-schema-validatorajv

ajv: fail validation in case of undefined field


If I analyze an object with explicit undefined fields (even the not required ones), I want the JSON Schema validation to fail.

It works as expected using z-schema package, but not with ajv.

Can I have the same behavior with ajv?

Here is a code example explaining the different outputs:

// run `node index.js` in the terminal
const Ajv = require('ajv');
const ajvOptions = {};
const ajv = new Ajv(ajvOptions);

const ZSchema = require('z-schema');
const zSchemaOptions = {};
const validator = new ZSchema(zSchemaOptions);

const schema = {
  type: 'object',
  properties: {
    notUndefinedString: {
      type: 'string',
    },
  },
  required: [],
};


const testObject = {
  notUndefinedString: undefined,
};

const ajvValid = ajv.validate(schema, testObject);
console.log('ajv -> is valid: ', ajvValid); // true, but should be false!

const zSchemaValid = validator.validate(testObject, schema);
console.log('ZSchema -> is valid: ', zSchemaValid); // false

working code running here: https://stackblitz.com/edit/node-ajv-vs-zschema-example?file=index.js


Solution

  • It seems not possible at the moment.

    Marked as a limitation on GitHub