using express-validator as Express middle ware not working

10,010

Solution 1

I think that the check method is already a middleware and there is no need to call it inside another middleware, your code should be:

exports.post_credit_check =  [
    body('firstName')
        .exists()
        .isAlphanumeric().withMessage('firstName should be alpanumeric')
        .isLength({min: 1 , max: 50}).withMessage('firstName should not be empty, should be more than one and less than 50 character')
        .trim(),
    function(req,res,next) { 
        var errorValidation = validationResult(req);
        if ( errorValidation ) {
            return res.status(500).json({
                title: 'an error occured',
                error: errorValidation
            });
        }
        next()
    },
    body('lastName')
        .exists()
        .isAlphanumeric().withMessage('lastName should be alpanumeric')
        .isLength({min: 1 , max: 50}).withMessage('lastName should not be empty, should be more than one and less than 50 character')
        .trim(),
    function(req,res,next) {

        var errorValidation = validationResult(req);
        if ( errorValidation ) {
            return res.status(500).json({
                title: 'an error occured',
                error: errorValidation
            });
        }
        next()
    }
];

Solution 2

Above solution is not working so I modified the solution with the latest documentation from https://express-validator.github.io/docs/next/index.html. Below solution is working perfectly for me.

exports.post_credit_check =  [
    body('firstName')
        .exists()
        .isAlphanumeric().withMessage('firstName should be alpanumeric')
        .isLength({min: 1 , max: 50}).withMessage('firstName should not be empty, should be more than one and less than 50 character')
        .trim(),
    function(req,res,next) { 
        var errorValidation = validationResult(req);
        if ( errorValidation.isEmpty() ) {
            return res.status(500).json({
                title: 'an error occured',
                error: errorValidation.array()
            });
        }
        next()
    },
    body('lastName')
        .exists()
        .isAlphanumeric().withMessage('lastName should be alpanumeric')
        .isLength({min: 1 , max: 50}).withMessage('lastName should not be empty, should be more than one and less than 50 character')
        .trim(),
    function(req,res,next) {

        var errorValidation = validationResult(req);
        if ( errorValidation.isEmpty() ) {
            return res.status(500).json({
                title: 'an error occured',
                error: errorValidation.array()
            });
        }
        next()
    }
];
Share:
10,010
made_in_india
Author by

made_in_india

Hi All , I love to play with perl and tcl. For now , I am developing an application in node in my free time.

Updated on June 04, 2022

Comments

  • made_in_india
    made_in_india almost 2 years

    I am using npm module [express-validator][1] to validate my query and body parameter. As in express , we can pass list of function as a middleware , I have created an separate file as validator. Here my code of the validator..

    creditcard.validator.js

    const { check, body , query ,oneOf, validationResult } = require('express-validator/check');
    
    exports.post_credit_check =  [
        function(req,res,next) { 
            body('firstName')
            .exists()
            .isAlphanumeric().withMessage('firstName should be alpanumeric')
            .isLength({min: 1 , max: 50}).withMessage('firstName should not be empty, should be more than one and less than 50 character')
            .trim();
            var errorValidation = validationResult(req);
            if ( errorValidation ) {
                return res.status(500).json({
                    title: 'an error occured',
                    error: errorValidation
                });
            }
            next()
        },
    
        function(req,res,next) {
        body('lastName')
        .exists()
        .isAlphanumeric().withMessage('lastName should be alpanumeric')
        .isLength({min: 1 , max: 50}).withMessage('lastName should not be empty, should be more than one and less than 50 character')
        .trim();
    var errorValidation = validationResult(req);
                if ( errorValidation ) {
                    return res.status(500).json({
                        title: 'an error occured',
                        error: errorValidation
                    });
                }
                next()
            }
    ];
    

    Here my the route file where I am passing the middleware validator array

    var express = require('express');
    var router = express.Router();
    var Creditcard =  require('../models/creditcard.model');
    const { validationResult } = require('express-validator/check');
    var validate = require('../models/creditcard.validate');
    
    router.post('/creditcarddetails', validate.post_credit_check , function(req, res, next) {
              .................
    }
    

    Though I am passing all middleware function in validate.post_credit_check, it not validating the body and not giving the error.

  • made_in_india
    made_in_india over 6 years
    After each validation I need to add anonymous function , is there any way in JS or any shortcut to avoid adding function code after each validation code in array.
  • YouneL
    YouneL over 6 years
    Yes, you can put all validation methods inside an array, and then create middlware to get the validation Result: router.post('/creditcarddetails', [check('param1')..., check('param2')..., check('param3')...], function (req,res,next) { var results = validationResult(req); ... });