Question:
I'm using Express-Validator to validate the data that the user enters.
router.post('/register', [check('email').not().isEmpty().withMessage('Enter an email.'), check('password', 'The password must be at least 6 characters').not().isEmpty()], checkData, registerPostRoute);
However, I think it's too polluted to put all these checks in there, before the next middleware. On the other hand, I can't pass these checks into the checkData
middleware so the code looks just like this:
router.post('/register', checkData, registerPostRoute);
I don't know if I'm doing it correctly, but does anyone know if it's possible to pass these checks into the checkData
middleware?
Answer:
Yes, it is possible. One way I do in my projects is to organize the validation middlewares in a dedicated file just for that.
Here is a suggestion for organizing the validation middlewares:
login.validator.js
const { body, validationResult } = require('express-validator');
exports.validationBodyRules = [
body('login', 'login is required').exists(),
body('password', 'password is required').exists(),
body('login', 'login is required').notEmpty(),
body('password', 'password is required').notEmpty()
];
exports.checkRules = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
};
In this example I make use of the body
validation function. In your case, just keep using check
.
It is also necessary to use the validationResult
function, it will serve to raise error messages and stop the chaining of middlewares, in this case I am launching status-code 400 (this is an implementation detail, but it is possible to launch its status-code
defined in the story provided for this feature).
After creating the validation middleware, just use it in the route you want, as follows:
route.js
const router = require('express').Router();
const loginService = require('../controllers/login.controller');
const loginValidator = require('../validators/login.validator');
router.post('/login', loginValidator.validationBodyRules, loginValidator.checkRules, loginService.logEmployee);
module.exports = router;
This is an example of organization I use in my projects, which is also the way of implementation recommended by the express-validator documentation .