0

In my website's routes file, I have a function like this:

router.post('/', ctrl1.validate, ctrl2.doSomething)

With the validate function looking like this:

function(req,res,next){
   var errors = validator.checkForm('myForm')
   if(errors){
      res.redirect("/")
   }else{
      next()
   }
}

If I want to pass parameters into the validator function (like the name of forms I want to validate) besides the implied req,res,next, how is that done? I have tried ctrl1.validate(formName) and ctrl1.validate(formName, req,res,next) with function(formName, req,res,next) in the controller, and neither work.

Isaac Krementsov
  • 646
  • 2
  • 12
  • 28
  • Have you tried using the body property of the request? So you would have the form names passed in the req.body, where you would then be able to pass in the name into the validator function? Or maybe you pass the entire form data in the body for validation? – Benjamin Charais Feb 17 '18 at 01:45

1 Answers1

0

The ideal solution would be to identify what form you're working on from the data passed with the request in the first place. You don't show what that is, so we don't know exactly what to recommend or if that is feasible in this case.

If you can't do that and want to have a generic function that you can use as a request handler in multiple places and you want to pass a parameter to it that is different in each of the different places you use it, then you need to create a function that returns a function.

router.post('/', ctrl1.validate("someFormName"), ctrl2.doSomething)

// definition of ctrl1.validate
validate: function(formName) {
   // return a request handler that will knkow which formName to use
   return function(req,res,next){
       var errors = validator.checkForm(formName)
       if(errors){
          res.redirect("/")
       } else {
          next()
       }
    }
}

When you first call this method, it returns another function that is your actual request handler. That inside function then has access to both req, res, next from the request and has access to the formName that was originally passed in.

jfriend00
  • 683,504
  • 96
  • 985
  • 979