Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add keyword Nullable (or allowNull) into Ajv?

Tags:

node.js

ajv

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

like image 767
Khusamov Sukhrob Avatar asked Aug 18 '17 06:08

Khusamov Sukhrob


1 Answers

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.

like image 181
esp Avatar answered Sep 20 '22 10:09

esp