3

I'm trying to assert that 2 passwords match:

app.post('/users/signup', [
    check('email', 'email is not valid')
      .isEmail()
      .trim(),
    check('password')
      .isLength({ min: 4 })
      .withMessage('password must be at least 4 characters')
      .equals('passwordConfirmation'),
  ], (req, res) => {
    ...

I'm using equals but it is checking if password actually equals the string 'passwordConfirmation' not the value req.body.passwordConfirmation

Julian Betancourt
  • 337
  • 2
  • 5
  • 11

1 Answers1

2

You can not use it the way you want.

I'm guessing, in your form, or your request body, you have two fields:

  • password
  • confirmPassword

Which you are able to access via:

  • req.body.password
  • req.body.confirmPassword

If this is correct, then you will not able to verify using the check API that the two are equal since you don't have access to the req object at the point and time.

What you can do is write a wrapper middleware around check:

const check = require('express-validator/check')

exports.verifyPasswordsMatch = (req, res, next) => {
    const {confirmPassword} = req.body

    return check('password')
      .isLength({ min: 4 })
      .withMessage('password must be at least 4 characters')
      .equals(confirmPassword)
}

Then use the wrapper like so:

app.post('/users/signup', [
    check('email', 'email is not valid')
      .isEmail()
      .trim(),
    verifyPasswordsMatch,
  ], (req, res) => {
    ...

Above is untested, but hopefully shows what you need to do.

Cisco
  • 20,972
  • 5
  • 38
  • 60
  • 1
    This isn't the best approach (and needs further code to work properly). express-validator has custom validators support, which have access to the `req` object. See https://stackoverflow.com/a/46013025/2083599 for details. – gustavohenke May 30 '18 at 06:24
  • the custom validator worked and I think is overall a better approach. Thanks guys! – Julian Betancourt Jun 02 '18 at 15:06