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

使用express-validator的isStrongPassword验证密码遇阻求助

问题排查与解决

你的密码验证不通过主要有两个核心问题:

1. isStrongPassword 规则配置格式错误

在checkSchema的验证规则中,带参数的验证方法(比如isStrongPassword)需要将参数放在options属性内,否则规则无法正确识别你设置的验证条件。

修正后的passwordSchema:

const passwordSchema = {
  trim: true,
  notEmpty: {
    bail: true,
    errorMessage: "Enter a valid password."
  },
  isStrongPassword: {
    options: {
      minLength: 8,
      minLowercase: 1,
      minUppercase: 1,
      minNumbers: 1
    },
    errorMessage: "Password doesn't match the requirements."
  }
};

2. POST请求参数获取方式错误

你当前从req.query获取参数,但POST请求的参数通常放在请求体(req.body)中,同时需要确保你的Express应用已经配置了解析请求体的中间件。

修正路由中的参数获取

router.post("/register", checkSchema({ username: usernameSchema, password: passwordSchema }), (req, res) => {
  const result = validationResult(req);
  if (result.isEmpty()) {
    res.json({
      username: req.body.username,
      password: req.body.password
    });
  } else {
    res.send({
      errors: result.array()
    });
  }
});

添加请求体解析中间件

在你的主应用文件(比如app.js)中添加:

const express = require('express');
const app = express();

// 解析JSON格式的请求体
app.use(express.json());
// 解析表单格式的请求体(如果需要处理表单提交)
app.use(express.urlencoded({ extended: true }));

完成以上修改后,输入符合要求的密码即可通过验证。

内容的提问来源于stack exchange,提问作者Jonas Q.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:35:16