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

如何在函数中使用express-validator实现密码确认校验

用函数方式实现express-validators密码确认校验

大家都推荐用数组方式做express-validators的校验,但我想搞清楚怎么用函数来实现。我自己写了一段代码,如下:

const checkPasswordConfirm = () => {
    body('password-confirm').custom((value, { req }) => {
        if(value !== req.body.password) {
            throw new Error('Passwords confirmation does not match password')
        }
    })
}

问题所在

你这段代码的核心问题是函数没有返回校验链对象。express-validators的body()方法会生成一个校验链,你的函数必须把这个对象返回出去,才能被Express的中间件机制识别并执行校验。另外,自定义校验函数里,校验通过时必须返回true,否则会被判定为校验失败。

修正后的代码

const checkPasswordConfirm = () => {
  // 返回body创建的校验链
  return body('password-confirm').custom((value, { req }) => {
    if (value !== req.body.password) {
      throw new Error('密码确认与输入的密码不匹配')
    }
    // 校验通过必须返回true
    return true;
  })
}

如何使用

在路由中直接调用这个函数,把它加入中间件链即可,和数组方式的使用逻辑一致:

app.post('/register', [
  checkPasswordConfirm(), // 调用函数作为校验中间件
  // 其他校验规则,比如校验密码格式、用户名等
], (req, res) => {
  // 处理注册请求逻辑
})

扩展优化(可选)

如果需要给密码确认字段加更多校验规则(比如不能为空、去除首尾空格),可以直接在body()后面链式调用相关方法:

const checkPasswordConfirm = () => {
  return body('password-confirm')
    .trim() // 去除首尾空格
    .notEmpty().withMessage('密码确认不能为空') // 校验非空
    .custom((value, { req }) => {
      if (value !== req.body.password) {
        throw new Error('密码确认与输入的密码不匹配')
      }
      return true;
    })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 19:52:08