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

使用express-validator自定义校验器时返回意外错误如何解决?

问题根因

你收到的Invalid value报错,核心原因是express-validator的custom校验器规则要求:

  • 校验不通过时主动抛出错误
  • 校验通过时必须返回真值(如true)或成功状态的Promise

你当前的自定义校验逻辑在products为非空数组的合法场景下没有任何返回值,默认返回undefined,会被框架判定为校验失败,触发默认的Invalid value错误提示。

修复方案

修改products字段的自定义校验逻辑,校验通过时主动返回true即可,修改后的校验代码如下:

const {check , validationResult} = require('express-validator');

exports.validateCreateOrder = [
   check("userId", "UserId is missing").not().isEmpty(),
   check("products").custom(products=>{
      if(!Array.isArray(products)) throw new Error('Products need to be an array')
      if (products.length == 0 ) throw new Error ('Product array cant be empty')
      // 校验通过时返回真值
      return true
   }),
   check("amount", "Amount is missing").not().isEmpty(),
   check("address", "Address is missing").not().isEmpty(),
(req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty())
      return res.status(400).json({ error: errors.array() });
    next();
},
]
其他排查项(可选)

如果修改后仍有问题,请确认你的express服务已经配置了JSON请求解析中间件,否则无法正确识别请求中的JSON参数:

// 服务入口文件中需要提前配置
app.use(express.json())

内容的提问来源于stack exchange,提问作者Ganesh Dagadi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:45:08