Search code examples
node.jsexpressexpress-validator

express-validator not producing validation errors


I am facing issues while trying express-validator v4.3.0.
There is one basic example of login with post request. There are two parameters email and password. Below is my code.

routes.js file:

var express = require('express');  
var router  = express.Router();  
var validator = require('./validator');

router.post('/login', [sanitize('email').trim(), 
 validator.publicRouteValidate('login')], (req, res, next) => {
  console.log(req);
}  

validator.js file:

'use strict';  
const { check, validationResult } = require('express-validator/check');  
const { matchedData, sanitize } = require('express-validator/filter');

module.exports = {  
  publicRouteValidate: function (method) {  
    return (req, res, next) => {  
      switch (method) {  
        case 'login':  
          check('email').isEmail().withMessage('email must be an email')  
            .isLength({min: 109}).withMessage('minimum length should be 100 characters')  
        break;  
      }  

      var errors = validationResult(req)
      console.log(errors.mapped())
      if (!errors.isEmpty()) {
         res.status(422).json({ errors: errors.array()[0].msg })
      } else {
         res.send('login')
      }
}}}  

Now when I am doing POST request with only email and value of email is abc. So I should get the error like email must be an email. But I did not get any response. So What is the issue I do not know?


Solution

  • Your publicRouteValidate function is only creating a validator, but it is never being called.

    This happens because, as documented, check returns an express middleware. Such middleware must be given to an express route in order for it to do its work.

    I recommend you to break that function in two: one that creates your validators, and another that checks the request for validation errors, returning earlier before touching your route.

    router.post(
        '/login',
        createValidationFor('login'),
        checkValidationResult,
        (req, res, next) => {
            res.json({ allGood: true });
        }
    );
    
    function createValidationFor(route) {
        switch (route) {
            case 'login':
                return [
                    check('email').isEmail().withMessage('must be an email'),
                    check('password').not().isEmpty().withMessage('some message')
                ];
    
            default:
                return [];
        }
    }
    
    function checkValidationResult(req, res, next) {
        const result = validationResult(req);
        if (result.isEmpty()) {
            return next();
        }
    
        res.status(422).json({ errors: result.array() });
    }