当对象模式无效时,如何强制 joi 调用自定义函数?

问题描述

我在 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",{ allowUnkNown: true,abortEarly: false }
);

console.log({ error });

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

解决方法

您不需要自定义验证来确保 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!!'})