问题描述
我尝试在两个字段之间进行验证。 foo
和 bar
。
我试着用
.when("bar",{ is: (v) => !!v,then: Joi.string().required() }),
但是 error
返回 undefined
不起作用。
知道如何解决这个问题吗?
const Joi = require("joi");
console.clear();
const schema = Joi.object({
foo: Joi.string()
.allow("",null)
.optional()
.min(2)
.max(10)
.when("bar",{
is: (v) => !!v,then: Joi.string().required()
}),bar: Joi.string().allow("",null).optional().min(2).max(10)
});
const { error } = schema.validate(
{ foo: null,bar: null },{ allowUnkNown: true,abortEarly: false }
);
const { error: error2 } = schema.validate(
{ foo: null,bar: "text" },abortEarly: false }
);
console.log({ error }); // should be with error.
console.log({ error2 }); // should be undefiend.
if (error) {
const { details } = error;
console.log({ details });
}
if (error2) {
const { details } = error2;
console.log({ details });
}
解决方法
这是你需要如何配置才能实现这一点
-
empty(['',null])
,将''
和null
视为undefined
。 -
or("foo","bar")
,要求其中之一。
const schema = Joi.object({
foo: Joi.string().empty(['',null]).min(2).max(10),bar: Joi.string().empty(['',null]).min(2).max(10)
}).or("foo","bar");