繁体   English   中英

当 object 架构无效时,如何强制 joi 调用自定义 function?

[英]How to force joi to invoke custom function when the object schema is invalid?

我在我的Joi模式中创建了一个自定义 function 来验证 name 是否equal confirmName

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

问题是当object中的验证失败时, custom function 不会调用。

目前结果birthYear仅适用于出生年份。 它应该是birthYearcustom

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

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

代码框.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 });
}

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

只需使用对值的引用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM