Joi 中的自定义验证未返回错误消息

问题描述 投票:0回答:1

我试图使用 Joi 验证使电子邮件唯一,方法是使用自定义验证函数检查它是否存在于数据库中,即使

console.log(user);

正在工作,我没有收到我制作的自定义函数的验证错误。

这是我的代码

const isUniqueEmail = async (value, helpers) => {
  const user = await User.query().where("email", value).first();

  if (user) {
    console.log(user);
    return helpers.error("any.invalid");
  }

  return value;
};

我从 Joi 文档中得到了这个 return helpers.error("any.invalid"); 但它不起作用 这就是我的目标

const videosSchema = Joi.object({
  channel_id: Joi.number().required().label("Channel Id"),
  email: Joi.string().required().custom(isUniqueEmail),
  title: Joi.string().required().min(5).max(50),
});

当电子邮件已被使用时,即使它正在记录用户,它也不会给我错误

但是其他验证正在起作用

node.js joi
1个回答
0
投票

正如文档所说:

any.custom(方法,[描述]) 添加自定义验证函数来执行任意代码,其中:

  • 方法 - 使用签名函数(值、助手)的自定义(仅限同步)验证函数

在您的情况下,isUniqueEmail不同步。我建议将验证移至业务层代码中。

© www.soinside.com 2019 - 2024. All rights reserved.