我写了下面的代码。
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
Run Code Online (Sandbox Code Playgroud)
但这行不通。如何编写这样的验证器?
即使compile函数始终返回true,也不会通过验证。
可以在节点沙箱中测试代码:https : //runkit.com/khusamov/59965aea14454f0012d7fec0
| 归档时间: |
|
| 查看次数: |
2457 次 |
| 最近记录: |