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

How to compare two fields in joi?

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

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

我试着用

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

但是 error return 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" },
  { 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 });
}

这是您需要如何配置才能实现的

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

这是 Joi 的处理方式:

const schema = Joi.object({
    password: Joi.string()
        .pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
    
    repeat_password: Joi.ref('password')
})
.with('password', 'repeat_password')

const { error } = schema.validate({ password: 'BlaBlaaa', repeat_password: 'Bla' })