[英]How can I use Joi to validate an object with unknown keys and check that the values are scalar types?
I have an object whose keys I cannot determine ahead of time.我有一个对象,我无法提前确定其键。 How can I enforce specific types (scalar types) for the values using Joi?
如何使用 Joi 为值强制执行特定类型(标量类型)?
Example object with unknown keys:具有未知键的示例对象:
const obj = {
x: "foo",
y: 7,
z: true,
p: { m: 1, n: false },
q: [ "a", "b", "c" ]
}
Since I only want to accept scalar
types, it means that keys p
and q
should cause a validation failure.由于我只想接受
scalar
类型,这意味着键p
和q
应该会导致验证失败。
How can I achieve this with Joi?我怎样才能用 Joi 实现这一目标?
So far I have tried this but it allows non-scalar values like ['a', 'b', 'c']
:到目前为止,我已经尝试过这个,但它允许像
['a', 'b', 'c']
这样的非标量值:
Joi.object().pattern(Joi.string(), Joi.boolean(), Joi.number())
Got it working with this得到它的工作
const validationSchema = Joi.object().pattern(
Joi.string(),
Joi.alternatives().try(Joi.number(), Joi.string(), Joi.boolean())
);
See sandbox查看沙箱
https://codesandbox.io/s/jovial-paper-hqiun https://codesandbox.io/s/jovial-paper-hqiun
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.