validate a password with express-validator

express, node.js, validation

Solution

Here is a cleaner & more complete solution:

File: routes/auth.route.js

const express = require('express');
const controller = require('../controllers/auth.controller');
const isAuth = require('../middleware/isAuth');
const {body} = require('express-validator');

const router = express.Router();

// Validators Definition:
.
.
.
const registerValidators = [
    .
    .
    .
    body('password')
        .exists({checkFalsy: true}).withMessage('You must type a password'),
    body('confirmedPassword')
        .exists({checkFalsy: true}).withMessage('You must type a confirmation password')
        .custom((value, {req}) => value === req.body.password).withMessage("The passwords do not match"),
];

// Routes Definition:
.
.
.
router.post('/register', ...registerValidators, controller.register);

module.exports.routes = router;

Note:

The name of the received parameter, inside the anonymous function passed into the custom validator, MUST be req. Not "request" nor anything else. Otherwise it won't work.

Problem

I'm using express-validator for express 3.x -- when the user changes their password or signs up for an new account, they have to enter their password twice. How would I write a custom validator that will push an error to the error stack in express-validator if the two passwords (two strings) do not match? Something like this: ``` req.assert('password1', 'Passwords do not match').isIdentical(password1, password2); var mappedErrors = req.validationErrors(true); ```

Original source