7

我写了以下代码。

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

但它不起作用。如何编写这样的验证器?

即使 compile 函数总是返回 true,它仍然没有通过验证。

代码可以在 Node-sandbox 中测试: https ://runkit.com/khusamov/59965aea14454f0012d7fec0

4

1 回答 1

17

您不能覆盖type关键字。null在 JSON 中是一个单独的数据类型,所以你需要"type": ["string", "null"]在你的模式中使用,不需要使用自定义关键字。

于 2017-08-18T07:20:28.327 回答