【发布时间】:2021-08-13 18:42:49
【问题描述】:
我尝试在两个字段之间进行验证。 foo 和 bar。
- 两者都应该是一个字符串,但它们是可选的。如果它们有一些值,则最小值应为 2,最大值为 10。
- 如果两者都为空(“”/null/undefined),则验证应该失败并返回错误。
我尝试这样做
.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" },
{ allowUnknown: true, 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 });
}
【问题讨论】:
-
您尝试过以下解决方案吗?
标签: javascript joi