10

I wrote the following code.

var ajv = new require('ajv');

ajv.addKeyword('allowNull', {
    type: 'null',
    metaSchema: {
        type: 'boolean'
    },
    compile: function(allowNullEnable, parentSchema) {
        return function(data, dataPath, parentData) {
            if (allowNullEnable) {
                return true;
            } else {
                if (parentSchema.type == 'null') {
                    return true;
                } else {
                    return data === null ? false : true;
                }
            }
        }
    }
});

var schema = {
  type: "object",
  properties: {
    file: {
      type: "string",
      allowNull: true
    }
  }
};

var data = {
   file: null
};

console.log(ajv.validate(schema, data)) // Expected true

But it does not work. How to write such a validator?

Even if the compile function always returns true, it still does not pass the validation.

The code can be tested in the Node-sandbox: https://runkit.com/khusamov/59965aea14454f0012d7fec0

Khusamov Sukhrob
  • 681
  • 1
  • 8
  • 22

1 Answers1

23

You cannot override type keyword. null is a separate data type in JSON, so you need to use "type": ["string", "null"] in your schema, there is no need to use a custom keyword.

esp
  • 7,314
  • 6
  • 49
  • 79
  • I need to create two keywords for the Swagger format. Such as nullable and descriminator. So I need this in the form of a keyword. The scheme can not be changed. – Khusamov Sukhrob Aug 18 '17 at 13:01
  • It can be done with inline keyword, but it's quite involved. See https://github.com/epoberezkin/ajv/issues/486 – esp Aug 18 '17 at 13:39
  • I read the issue. If I understand correctly, there is no solution and will not be? – Khusamov Sukhrob Aug 19 '17 at 08:35
  • It can be done with inline keyword and it will only work in allErrors: true mode. You cannot change type validation process but you can analyse and modify collected errors, in the same way ajv-errors does, so if type validation fails but the data is null and nullable: true you will remove the error. – esp Aug 19 '17 at 11:32