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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With