在AJV JSON模式中,可以通过使用AJV上下文中可用的refs关键字来引用模式中另一个元素的值。这可以通过使用JSON指针语法完成。
下面是一个示例,它演示了如何验证一个名为person的对象,该对象具有一个属性age,该属性的值必须小于或等于最大年龄,而最大年龄存储在模式中的元素中。
{
"$id": "http://example.com/schemas/person.json",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer",
"maximum": { "$data": "1/maxAge" }
}
},
"required": ["name", "age"],
"definitions": {
"personInfo": {
"type": "object",
"properties": {
"maxAge": {
"type": "integer"
}
},
"required": ["maxAge"]
}
}
}
在这个例子中,$data: "1/maxAge"引用了模式中定义的personInfo元素的maxAge属性的值。
要验证一个person对象,可以使用以下代码:
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = require('./person.json');
const person = { name: 'John', age: 30 };
const personInfo = { maxAge: 40 };
const valid = ajv.validate(schema, person, { maxAge: personInfo.maxAge });
console.log(valid); // 输出 true