field_name: {
type: "object",
properties: {
min: { type: "number", minimum: 0, maximum: 600 },
max: { type: "number", minimum: 0, maximum: 600 },
},
required: ["min", "max"],
additionalProperties: false,
},
我正在使用ajv来验证节点中的对象。
对于上面的对象,我如何进一步指定max
必须总是大于min
?
你实际上可以在另一个模式中使用为一个属性提供的数据,但你需要在创建Ajv实例时启用$data
作为选项:
注意:$data
是一个JSON指针
const ajv = new Ajv({$data: true});
const validate = ajv.compile({
type: 'object',
properties: {
min: {
type: 'number',
minimum: 0,
exclusiveMaximum: 600
// i.e. min >= 0 and min < 600
},
max: {
type: 'number',
exclusiveMinimum: {$data: "1/min"},
maximum: 600
// i.e. max > min and max <= 600
}
}
});
const test = (obj) => {
const res = validate(obj);
console.log(`{min: ${obj.min}, max: ${obj.max}} -> ${res}`);
if (!res) console.log(validate.errors);
return res;
}
test({min: 0, max: 500}); // true
test({min: 500, max: 0}); // false
test({min: 200, max: 200}); // false
test({min: 599, max: 600}); // true
test({min: 600, max: 600}); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/8.11.2/ajv7.bundle.js" integrity="sha512-gopWbU/o40XPlW4g/zJHfBUj1z9LKAWK6ZBFH5xiJHDDRRm8cXBo5UMLYTG5G42Pce8pBaWVNozLmvulanI3uQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
const {ajv7: Ajv} = window;
</script>