问题描述
我一直在尝试嵌套 where 验证,但到目前为止没有运气。这是我想要实现的目标:
1- 如果 mainType 是 COMMERCIAL,则为 contactMethod 定义所需的架构。 2- 如果 isHousing 为 true,则为 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,})
.required(),otherwise: Joi.disallow(),})
我也试过这个:
contactMethod: Joi.when('mainType',{
switch: [
{
is: 'COMMERCIAL',then: Joi.object()
.keys({
create: Joi.object({
message: Joi.string().allow(''),})
.required(),},{
is: 'REAL_ESTATE',then: Joi.when('isHousing',{
is: true,then: Joi.object()
.keys({
create: Joi.object({
message: Joi.string().allow(''),})
.required(),}),],})
那么我在这里做错了什么?
解决方法
好的,我是这样解决的:
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() 更改为禁止。
希望这对未来的人有所帮助。
,就像你在第一层所做的那样 - 使用 .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(''),otherwise: Joi.disallow(),});