'How "equals" in express-validator works?

I have to validate two fields are equals. In this case both passwords are the same. The problem it is that the "equals" from express-validator is not working.

This is the code:

app.post('/register', [
 isNotLogged,
 check('email', 'The email must be a valid one').isEmail(),
 check('nickname', 'The nickname must be filled').notEmpty(),
 check('password', 'The password must contain minimum eight characters, at least one letter and one number')
    .matches("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"),

 //This is not working
 check('passwordConfirm', 'The passwords must match').equals('password'),

 validateResults
], register)


Solution 1:[1]

Unfortunately Express-Validator doesn't work with Validator.js's equals(), you'll have to use one of Express-Validator's middlewares and not its Validator.js affility.

Here is an example straight from Express-Validator's website which seems fit your use case:

  body('oldPassword')
  // if the new password is provided...
  .if((value, { req }) => req.body.newPassword)
  // OR
  .if(body('newPassword').exists())
  // ...then the old password must be too...
  .notEmpty()
  // ...and they must not be equal.
  .custom((value, { req }) => value !== req.body.newPassword);

You do not need to use Express-Validator's check middleware as you are throwing away your ability to utilise Validator.js's validators. Instead of check you could use isEmail() and exists() (an Express-Validator validator). Also, you don't need to have your middlewares as part of an array (although you can):

app.post('/register',
    isNotLogged,
    body('email').isEmail().withMessage('The email must be a valid one').bail().trim(),
    body('nickname').exists({ checkNull: true }).withMessage('The nickname must be filled').bail().trim(),
    body('password').trim().if((value, { req }) => (typeof req.body.passwordConfirm !== 'undefined')).bail().custom((value, { req }) => value !== req.body.passwordConfirm).withMessage('The email must be a valid one').bail().trim().matches("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"),
    validateResults,
    register
);

Here the body() function would come from const { body } = require('express-validator') theres a few others similar for query paramaters, header parameters ect, all are documented here.

I also used some trim()s and bails()s just to be safe. You can read up on those here and here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 codeguy