Joi多重条件 [英] Joi multiple when condition

查看:79
本文介绍了Joi多重条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对Joi进行体内验证,但似乎永远无法正常工作,并且会一直处于相同的状态. 因此,如果我 POST 与此

I want to do a validation with Joi in my body, but it seems never work and fall all the time in the same condition. So if i POST with this

终点: /elasticSearch?eType = scroll& scroll = 1h

endPoint: /elasticSearch?eType=scroll&scroll=1h

身体:{}

应该抛出错误的原因,因为eType是 scroll ,在这种情况下,需要 scroll_id ,而不是null,不为空.

that supposed to throw an error, because eType is scroll and in this case scroll_id need to be required,not null, not empty.

即使我为此 POST

终点: /elasticSearch?eType = search& scroll = 1h

endPoint: /elasticSearch?eType=search&scroll=1h

身体:{}

应该抛出错误,因为eType是 search ,在这种情况下,需要 query 必填.

that supposed to throw an error, because eType is search and in this case query need to be required.

使用这些代码,

在一种情况下,它总是像没有验证一样通过,即使他们不应该通过我的看法;在第二种情况下,我得到了错误:查询是必需的,而我每次执行时都需要scroll_id打电话.

in one case it just always pass like if it's had no validation even if they should not pass in my opinion and in the second case, i got error: query is required, and scroll_id is required all the time when i make a call.

所以有人可以帮助我理解为什么这些验证是错误的吗?

so someone can help me to understand why these validation are wrong ?

谢谢

默认情况下,如果我这样做:

By default, if i do that like this:

body: 
  { 
    query: 
     Joi.alternatives()
     .when(Joi.ref('$query.eType'), 
      { 
       is: Joi.string().equal('search'), 
       then: Joi.required() 
      }
     ), 
   scroll_id: 
    Joi.alternatives() 
     .when(Joi.ref('$query.eType'), 
     { 
      is: Joi.string().equal('scroll'), 
      then: Joi.required() 
     }
    ) 
   }

这始终需要查询和scroll_id.

That required query and scroll_id all time.

推荐答案

直接从文档中复制.

使用Joi验证对象时,其他输入的值 (即标头,查询,参数,有效负载和身份验证)可用 在验证上下文中(可在规则中访问为 Joi.ref('$ query.key')).

When using a Joi validation object, the values of the other inputs (i.e. headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).

因此,请在您的 eType 引用中使用Joi.ref('$query.eType'),因为您正在尝试根据查询参数来验证有效负载,因此在验证阶段,它们在单独的范围内.

So, use Joi.ref('$query.eType') in your eType references, because you are trying to validate payload according to query parameters, in the validation phase, they are in separate scopes.

Joi.alternatives()
   .when(Joi.ref('$query.eType'), {
     is: Joi.string().equal('search'),
     then: Joi.required()
   })

这篇关于Joi多重条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆