12

我正在使用 express 3.x 的 express-validator - 当用户更改密码或注册新帐户时,他们必须输入两次密码。

如果两个密码(两个字符串)不匹配,我将如何编写一个自定义验证器,它将错误推送到 express-validator 中的错误堆栈?

像这样的东西:

req.assert('password1', 'Passwords do not match').isIdentical(password1, password2);
var mappedErrors = req.validationErrors(true);
4

5 回答 5

20

我找到了答案

req.assert('password2', 'Passwords do not match').equals(req.body.password1);
var mappedErrors = req.validationErrors(true);
于 2012-09-23T00:31:46.333 回答
5

This one works!

req.checkBody('password2','Passwords do not match.').equals(req.body.password1);
var errors = req.validationErrors();

notice the use of checkBody() in this case

于 2016-07-27T15:14:53.453 回答
3

这是我找到的答案

const { body } = require('express-validator/check');
app.post('/user', body('passwordConfirmation').custom((value, { req }) => {
if (value !== req.body.password) {
    throw new Error('Password confirmation does not match password');
    }
  }), (req, res) => {
// Handle the request
});`

检查此文档https://express-validator.github.io/docs/custom-validators-sanitizers.html

于 2018-08-14T15:14:12.740 回答
1

正确方法: express-validator doc:检查密码确认是否与密码匹配

const RegistrationRules = [
  check("password")
    .notEmpty().withMessage("Password should not be empty"),
  check("confirmPassword")
    .notEmpty().withMessage("Confirm Password should not be empty")
    .custom((value,{req}) =>{
        if(value !== req.body.password){
            throw new Error('Password confirmation does not match with 
            password')
        }
        return true;
    }),]
于 2022-01-04T07:02:42.737 回答
0

我用自定义方法制作它:

.custom(() => {
      if (req.body.password === req.body.confirmPassword) {
        return true;
      } else {
        return false;
      }
    })

这是密码验证器的完整代码:

exports.userRegisterValidator = (req, res, next) => {

//
  // ─── CHECK FOR PASSWORD ─────────────────────────────────────────────────────────
  //
  req
    .check("password", "Password is required")
    .notEmpty()
    .isLength({
      min: 6
    })
    .withMessage("Password must contain at least 6 characters")
    .isLength({
      max: 20
    })
    .withMessage("Password can contain max 20 characters")
    .custom(() => {
      if (req.body.password === req.body.confirmPassword) {
        return true;
      } else {
        return false;
      }
    })
    .withMessage("Passwords don't match.");

  //
  // ─── CHECK FOR ERRORS ───────────────────────────────────────────────────────────
  //
  const errors = req.validationErrors();

  // if error show the first one as they happen
  if (errors) {
    const firstError = errors.map(error => error.msg)[0];
    return res.status(400).json({ error: firstError });
  }

  // proceed to next middleware
  next();
};

于 2019-03-19T16:52:50.367 回答