Search code examples
node.jsexpressexpress-validator

How do I Solve Express Validator Middleware Error?


First, I have userController like this:

File userController.js

const { validationResults } = require('express-validator');
const { userSignUpValidation } = require('../validator/userSignUpValidate');


function userCreation(req, res) {
    try{
        const errors = validationResults(req);
        if(errors) {
            return res.status(400)
            .json({
                error: {
                    message: errors.array()[0].msg
                }
            })
        }

        bcrypt.hash(req.body.userPassword, saltRounds, function(err, hash) {
            User.create({
                userId: req.body.userId,
                userEmail: req.body.userEmail,
                userPhoneNumber: req.body.userPhoneNumber,
                userPassword: hash
            })
            .then((user) => {
                return res.status(200).json(user);
            })
            .catch((error) => {
                return res.status(400).json.error;
            });
        });
    } catch(error) {
        return res.status(400)
        .json({
            error: {
                message: error
            }
        })
    }
}

In the validator/userSignUpValidate.js the code like this:

'use strict'

const { check } = require('express-validator');

module.exports = [
    check('userId').isLength({ min: 5 }).withMessage('The username at least more than 5 characters!'),
    check('userPassword').isLength({ min: 6 }).withMessage('The password at least more than 6 characters!'),
    check('userPhoneNumber').isLength({ min: 10 }).withMessage('The phone number at least more than 10 characters!'),
    check('userEmail').isEmail().withMessage('Is your email correct? Please be correct!')
]

When I test it on postman, the json response always show error by catch on userController.js without error message.

{
    "error": {
        "message": {}
    }
}


My question. To ensure the express-validator run in the right place, where should I put the code?


Solution

  • Firstly you need to import validationResult from express-validator, in your code you are importing validationResults.

    Secondly, you are not using your userSignUpValidate middleware. This middleware can be used in controller but it is better to appy it in the userRoute to keep controller clean.

    So let's apply userSignUpValidate middleware to the userRoutes. If the file paths don't match yours, please fix them.

    const express = require("express");
    const router = express.Router();
    const usersController = require("../controllers/userController");
    const userSignUpValidate = require("../validator/userSignUpValidate");
    
    router.post("/register", [userSignUpValidate], usersController.userCreation);
    
    module.exports = router;
    

    Then in the controller, we need to import validationResult from express-validator and use it:

    const { validationResult } = require("express-validator");
    
    function userCreation(req, res) {
      try {
        const errors = validationResult(req);
        if(!errors.isEmpty()) {
          console.log(errors);
          return res.status(400).json({
            error: {
              message: errors.array()[0].msg
            }
          });
        }
    
        //other code you have
      } catch (error) {
        return res.status(400).json({
          error: {
            message: error
          }
        });
      }
    }
    
    exports.userCreation = userCreation;
    

    When we send a request body with a 3 character password like this:

    {
      "userId": "userid",
      "userPassword": "123",
      "userPhoneNumber": "1234567890",
      "userEmail": "abc@gmail.com"
    }
    

    The response will be like this with a 400 - Bad Request:

    {
        "error": {
            "message": "The password at least more than 6 characters!"
        }
    }