快速验证器错误检查

express-validator wrong check

我正在使用 express-validator 5.3.1。我这样定义密码检查:

check('password')
  .not().isEmpty().withMessage('Password can\'t be null')
  .isString()
  .isLength({ min: 8 }),
check('retypePassword')
  .not().isEmpty().withMessage('Password can\'t be null')
  .isString().withMessage('Password must be a string')
  .custom((value, { req }) => {
    if(value.trim() !== req.body.password.trim()) {
      throw new Error ('Password confirmation does not match password');
    }
  }),

为了测试,我发送了相同的密码并重新输入密码 ('password'),但出现了错误:

[ { "location": "body", "param": "retypePassword", "value": "password", "msg": "Invalid value" } ]

我定义了 message 并且 retypePassword 全部错误,这是怎么回事?

当您实施 custom 验证时,如果验证成功,您必须 return true,否则您将收到 "Invalid value" 错误消息。所以你只需添加一个 return true; 这样的语句

.custom((value, { req }) => {
    if(value.trim() !== req.body.password.trim()) {
        throw new Error ('Password confirmation does not match password');
    }
    return true;
})