【问题标题】:How to force joi to invoke custom function when the object schema is invalid?对象模式无效时如何强制joi调用自定义函数?
【发布时间】:2021-04-29 18:58:44
【问题描述】:

我在我的 Joi 架构中创建了一个自定义函数来验证名称是否为 equalconfirmName

我使用abortEarly: false 来获取所有错误。

问题是当object 中的验证失败时custom 函数没有调用。

目前结果输出仅适用于birthYear。应该是birthYearcustom

有没有办法让它像我描述的那样工作?

{ name: "foo", confirmName: "oo", birthYear: 0 },

codesandbox.io

const Joi = require("joi");

console.clear();

const schema = Joi.object({
  name: Joi.string(),
  confirmName: Joi.string(),
  birthYear: Joi.number().integer().min(1900).max(2013)
}).custom((doc, helpers) => {
  const { name, confirmName } = doc;
  if (name !== confirmName) {
    throw new Error("name not match!!");
  }
});

const { error } = schema.validate(
  { name: "foo", confirmName: "oo", birthYear: 0 },
  { allowUnknown: true, abortEarly: false }
);

console.log({ error });

if (error) {
  const { details } = error;
  console.log({ details });
}

【问题讨论】:

    标签: javascript joi


    【解决方案1】:

    您不需要自定义验证来确保 name 等于 confirmName

    只需使用reference to the value

    const schema = Joi.object({
      name: Joi.string(),
      confirmName: Joi.ref('name'),
      birthYear: Joi.number().integer().min(1900).max(2013)
    });
    

    如果你想覆盖错误信息,你可以使用.messages:

    confirmName: Joi.string().required()
                             .valid(Joi.ref('name'))
                             .messages({'any.only': 'name not match!!'})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      相关资源
      最近更新 更多