You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在express-validator验证Schema中使用自定义验证器报错求助

express-validator自定义验证器报错this.validator is not a function解决方法

问题现象

在express-validator的验证Schema中配置email字段的异步custom验证器时,未触发自定义错误提示,反而抛出this.validator is not a function错误。

错误原因

schema风格的验证配置里,custom验证器不能直接赋值为函数,必须将验证函数包裹在options属性中。express-validator内部期望custom是一个包含验证逻辑的对象,直接传递函数会导致内部调用时无法找到正确的验证方法。

修复后的验证Schema配置

email: {
  isLength: {
    options: {
      max: 40,
    },
    errorMessage: "Email must be between 5 and 15 characters in length",
  },
  notEmpty: {
    errorMessage: "Email must not be empty.",
  },
  isEmail: {
    errorMessage: "Invalid email.",
  },
  isString: {
    errorMessage: "Email must be a string.",
  },
  custom: {
    options: async (email) => {
      const isExist = await fetchUserByEmailOrID(email);
      if (isExist.length) {
        throw new Error("A user already exists with this e-mail address");
      }
    },
    // 可选:也可以在这里统一设置错误信息,替代throw语句
    // errorMessage: "A user already exists with this e-mail address"
  },
},

额外优化:控制器验证结果判断

原注册控制器中验证结果的判断逻辑可优化为更清晰的写法:

const result = validationResult(req);
if (!result.isEmpty()) {
  return res.status(400).json({
    status: 400,
    message: result.errors,
  });
}

result.isEmpty()是express-validator提供的API,用于直接判断是否存在验证错误,比手动判断errors.length更直观可靠。

内容的提问来源于stack exchange,提问作者johnny shepherd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 18:40:12