DEV Community

Discussion on: A Clean Approach to Using Express Validator

Collapse
 
gallib_net profile image
Alain

Very useful thanks!

For my purpose I just split validators.js in 2 parts, your validate const is for me a separate middleware in which I've also added a

req.matchedData = matchedData(req) 
Enter fullscreen mode Exit fullscreen mode

useful to me to access to validated data in next middleware.

My validateRules middleware looks like:

import { matchedData, validationResult } from 'express-validator';

const validateRules = (req, res, next) => {
    const errors = validationResult(req);

    if (errors.isEmpty()) {
        req.matchedData = matchedData(req);
        return next();
    }

    const extractedErrors = [];
    errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }));

    return res.status(422).json({
        errors: extractedErrors,
    });
}

export default validateRules;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nedsoft profile image
Chinedu Orie

That was insightful. Thanks for sharing!

Collapse
 
arnabmunshi profile image
ARNAB MUNSHI

hi Alain

import { matchedData, validationResult } from 'express-validator';

This line not working for me. I don't know why.

But the following code is work for me.

import expressValidator from "express-validator";
const { body, validationResult } = expressValidator;