我一直试图得到嵌套的验证,但没有运气到目前为止。以下是我想要实现的:
1-如果mainType是COMMERCIAL,那么为contactMethod定义所需的模式。2-如果ishhousing为真,则为contactMethod定义所需的模式。3-如果mainType是REAL_ESTATE,则禁止传递contactMethod对象
以下是我失败的尝试:
contactMethod: Joi.when('mainType', {
is: 'COMMERCIAL',
then: Joi.object()
.keys({
create: Joi.object({
message: Joi.string().allow(''),
}).required(),
})
.required()),
}).when('isHousing', {
is: true,
then: Joi.object()
.keys({
create: Joi.object({
message: Joi.string().allow(''),
}).required(),
})
.required(),
otherwise: Joi.disallow(),
})
我也试过这个:
contactMethod: Joi.when('mainType', {
switch: [
{
is: 'COMMERCIAL',
then: Joi.object()
.keys({
create: Joi.object({
message: Joi.string().allow(''),
}).required(),
})
.required(),
},
{
is: 'REAL_ESTATE',
then: Joi.when('isHousing', {
is: true,
then: Joi.object()
.keys({
create: Joi.object({
message: Joi.string().allow(''),
}).required(),
})
.required(),
}),
otherwise: Joi.disallow(),
},
],
})
我哪里做错了?
就像你在第一层做的那样-使用.keys({})
来定义对象属性。
contactMethod: Joi.when('mainType', {
is: 'COMMERCIAL',
then: Joi.object()
.keys({
create: Joi.object() // You missing usage of Joi.object()
.keys({ // should define object attribute here
message: Joi.string().allow(''),
})
.required(),
})
.required(),
}).when('isHousing', {
is: true,
then: Joi.object()
.keys({
create: Joi.object() // the same :|
.keys({
message: Joi.string().allow(''),
})
.required(),
})
.required(),
otherwise: Joi.disallow(),
});
我是这样解决的:
contactMethod: Joi.when('mainType', {
is: 'COMMERCIAL',
then: Joi.object()
.keys({
create: Joi.object()
.keys({
message: Joi.string().allow(''),
})
.required(),
})
.required(),
otherwise: Joi.when('isHousing', {
is: true,
then: Joi.object()
.keys({
create: Joi.object()
.keys({
message: Joi.string().allow(''),
})
.required(),
})
.required(),
otherwise: Joi.forbidden(),
}),
})
我的尝试没有包含键({}),正如上面的@hoangdv所建议的,我还需要将disallow()更改为forbidden。
希望这对将来的人有所帮助。