[英]Conditional headers using Joi
I'm using Joi to validate the headers on a HTTP request. 我正在使用Joi验证HTTP请求中的标头。 I have two headers.
我有两个标题。 If FOO is present then BAR is required, otherwise BAR is optional.
如果存在FOO,则需要BAR,否则BAR是可选的。 This works:
这有效:
'FOO': Joi.string().optional(),
'BAR': Joi.string().when('FOO', { is: Joi.not(''), then: Joi.required() })
If I want FOO to be a numeric value then this works: 如果我希望FOO是一个数值,则可以使用:
'FOO': Joi.number().integer().default(0).optional(),
'BAR': Joi.string().when('FOO', { is: Joi.number().min(1), then: Joi.required() })
However if I omit the default(0) then Joi thinks that BAR is required when FOO is not present. 但是,如果我省略default(0),那么Joi认为当FOO不存在时,需要BAR。 Is that correct behavior?
那是正确的行为吗? Is there a better way to handle this?
有没有更好的方法来解决这个问题?
This can be made a lot simpler by using .with()
. 通过使用
.with()
可以使此过程变得简单得多。 Consider the following schema: 考虑以下架构:
const schema = Joi.object().keys({
FOO: Joi.number().default(0).min(1),
BAR: Joi.string()
}).with('FOO', 'BAR');
The .with()
forces BAR
to be required only when FOO
is present. .with()
强制仅在FOO
存在时才需要BAR
。
Also similar to your example it will also ensure FOO
must be greater than or equal to 1
if it's actually in the payload, else Joi will default it to 0
. 同样类似于您的示例,它还可以确保
FOO
实际上在有效负载中必须大于或等于1
,否则Joi会将其默认设置为0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.