【发布时间】:2021-09-06 12:04:55
【问题描述】:
我正在编写以下代码,我必须在其中使用 Joi 库执行一些验证。
验证解释如下:当type 等于ABC 并且在数组arrayOfObjects 中有一个objectInArray.id 等于允许值范围内的特定值(在这种情况下,UUID @ 987654325@) 并且当对象anotherObjectInArray 不为空时,则objectToValidate 应该存在,并具有必需的属性field1 和field2,否则objectToValidate 是可选的。
const data = {
type: "ABC",
arrayOfObjects: [
{
objectInArray: {
id: '012345ab-c678-910d-e111-f21g3h14i15j',
value: "test"
},
anotherObjectInArray: {
some_field: "some_value"
},
otherData: "...",
},
{
objectInArray: {
id: '161718kl-m192-021n-o222-p32q4r25s26t',
value: "test2"
},
otherData: "..."
}
],
objectToValidate: {
field1: "value",
field2: true
}
}
我尝试进行以下验证,但失败了。
objectToValidate: Joi.when('type', {
is: 'ABC',
then: Joi.when('arrayOfObjects', {
is: Joi.array().items(Joi.object({
objectInArray: Joi.object({
id: Joi.string().guid().required().valid('012345ab-c678-910d-e111-f21g3h14i15j', 'other_uuid')
}).required()
}).required()),
then: Joi.when('arrayOfObjects', {
is: Joi.array().items(Joi.object({
anotherObjectInArray: Joi.object().not(null)
})),
then: Joi.object({
field1: Joi.string().required(),
field2: Joi.boolean().strict().required()
}).required(),
otherwise: Joi.object().optional()
}),
otherwise: Joi.object().optional()
}),
otherwise: Joi.object().optional()
})
谁能指出我的代码有什么问题? :)
【问题讨论】:
标签: node.js validation hapijs joi hapi