2

I have two functions to validate the request body, validation1 and validation2. Now my task is, after parsing the incoming request body, I need to validate the data with validation1 if the user role is premium user, otherwise I will validate the data using validation2.

I have tried to solve it like the following but to no avail. For some reason, the validation middlewares are not getting called.

const express = require('express');
const router = express.Router();
   
const { userController } = require('./controllers');

router.route('/check').post(
  (req, res, next) => {
    if (req.role === 'premium user') {
      validation1(someInformation);
    } else {
      validation2(someInformation);
    }
    next();
  },
  userController.check
);


const validation1 = (someInformation) => (req, res, next) => {
  // codes
  return next();
}

const validation2 = (someInformation) => (req, res, next) => {
  // codes
  return next();
}

Any help would be appreciated. Thanks in advance.

MI Sabic
  • 367
  • 2
  • 7
  • 18

1 Answers1

3

You should pass callback function next to validate function.

Also change your validation function like below code:

const express = require('express');
const router = express.Router();
   
const { userController } = require('./controllers');

router.route('/check').post(
  (req, res, next) => {
    if (req.role === 'premium user') {
      validation1(req, res, next);
    } else {
      validation2(req, res, next);
    }
  },
  userController.check
);


const validation1 = (req, res, next) => {
  // codes
  return next();
}

const validation2 = (req, res, next) => {
  // codes
  return next();
}
Pooya
  • 2,968
  • 2
  • 12
  • 18
  • I have edited my code a bit. Can you please check my code again? – MI Sabic Oct 20 '21 at 15:53
  • `validation1` and `validation2` are your functions, you may pass any number of arguments. If you need to pass a few more arguments then you can pass during calling like `validation1(someInformation, req, res, next);` and accept when you define like `const validation1 = (someInformation, req, res, next) => {` – Arif Khan Oct 20 '21 at 16:03
  • Why create function like that `const validation1 = (someInformation) => (req, res, next) =>`? If create function like that, you have two call function twice `validation1(someInformation)(req, res, next)` – Pooya Oct 20 '21 at 16:08