如何比较joi中的两个字段?

问题描述

我尝试在两个字段之间进行验证。 foobar

  1. 两者都应该是一个字符串,但它们是可选的。如果它们有一些值,则最小值应为 2,最大值应为 10。
  2. 如果两者都为空 (""/null/undefined),则验证应该失败并返回错误

我试着用

.when("bar",{ is: (v) => !!v,then: Joi.string().required() }),

但是 error 返回 undefined 不起作用。

知道如何解决这个问题吗?

codesandbox.io

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

解决方法

这是你需要如何配置才能实现这一点

  1. empty(['',null]),将 ''null 视为 undefined
  2. 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");