Search code examples
node.jsvalidationexpressexpress-validator

Express Validator: How parameters passed to validator functions


I am curious how the parameters are passed to validator middleware, the excerpt is taken from express-validator, e.g., programming_language is passed to check() function.

const { check, oneOf, validationResult } = require('express-validator/check');
app.post('/start-freelancing', oneOf([
  check('programming_language').isIn(['javascript', 'java', 'php']),
  check('design_tools').isIn(['photoshop', 'gimp'])
]), (req, res, next) => {
  try {
    validationResult(req).throw();

    // yay! we're good to start selling our skilled services :)))
    res.json(...);
  } catch (err) {
    // Oh noes. This user doesn't have enough skills for this...
    res.status(422).json(...);
  }
});

Solution

  • check('programming_language')
    

    'programming_language' is a request parameter. No need to pass anything separately. It picks up from

    req.body.programming_language
    req.cookies.programming_language
    req.headers.programming_language
    req.params.programming_language
    req.query.programming_language
    

    Same thing for 'design_tools'

    req.body.design_tools
    req.cookies.design_tools
    req.headers.design_tools
    req.params.design_tools
    req.query.design_tools