node.js - How add keyword Nullable (or allowNull) into Ajv? -
i wrote 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 not work. how write such validator?
even if compile function returns true, still not pass validation.
the code can tested in node-sandbox: https://runkit.com/khusamov/59965aea14454f0012d7fec0
you cannot override type
keyword. null
separate data type in json, need use "type": ["string", "null"]
in schema, there no need use custom keyword.
Comments
Post a Comment