【发布时间】:2019-11-01 09:51:24
【问题描述】:
我需要使用动态对象来验证值。该对象定期更改,因此我在运行时将其下载并在本地保存为格式良好的 .json 文件。我需要将这些值输入到对Joi.validate 的调用中(通过'context' 选项)并验证数组中的项目是否与上下文对象中的键/值对之一匹配。
// the defined schema
const schema = Joi.object().keys({
'foo': Joi.array()
.unique()
.items(
// these items need to match the keys/values from the context object
Joi.object().keys({
id: Joi.string()
.required(), // this needs to be a key from the context object
name: Joi.string()
.required(), // this needs to be the value from the context object for the key defined by the above id property
}),
)
})
// the .json file with the context object looks as such
{
"id of first thing": "name of first thing",
"id of second thing": "name of second thing",
...
}
// validation is done like this:
Joi.validate(theThingsToValidate, schema, {context: objectFromTheJsonFile});
【问题讨论】:
-
您从未指定您是否遇到错误或它不起作用或您应该如何编写代码?
标签: javascript json validation schema joi