Joi multiple when condition

我怕爱的太早我们不能终老 提交于 2020-01-03 04:38:24

问题


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

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

Body:{}

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

even when i POST with this

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

Body:{}

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

so with these codes,

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 ?

Thanks

Update

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() 
     }
    ) 
   }

That required query and scroll_id all time.


回答1:


Directly copied from documentation.

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')).

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()
   })


来源:https://stackoverflow.com/questions/54467550/joi-multiple-when-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!