【问题标题】:How to compare two fields in joi?如何比较joi中的两个字段?
【发布时间】:2021-08-13 18:42:49
【问题描述】:

我尝试在两个字段之间进行验证。 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" },
  { 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


【解决方案1】:

这是您需要配置以实现该目标的方式

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多