express-validator on PUT methods

Viewed 303

I'm creating an API and decided to use express-validator for validation (duh), I've never used this before so I'm unsure on some aspects of it so my validations might not be the best but I'm getting by.

I have built two validation middle ware using this and export them from the same folder like this:

module.exports = {
  create: require('./create'),
  update: require('./update')
}

So I can then do this in my router:

const validation = require('../validations/plotValidation')

// ...

router.get('/', controller.all)
router.post('/create', validation.create(), controller.create)
router.get('/:plotId', controller.read)
router.put('/:plotId/update', validation.update(), controller.update)
router.delete('/:plotId/delete', controller.delete)

// ...

I'm not good enough with express-validator to do both validate both routes with the same file, maybe I'll try it at some point, anyway.

The .post method works fine and validates everything I want it to however the .put method just seems to be ignoring every check here are is file in case you want to see the checks:

const { body, check, param } = require('express-validator');

module.exports = () => {
  return [
    param('plotId')
      .exists().withMessage('URI requires plot id'),

    body('price')
      .optional()
      .isObject()
  ]
}

As you can probably tell I only just stated it, but even with only these two tiny checks it just doesn't seem to run.

Does express-validator not work on PUT methods?

1 Answers

For anyone else who has this issue I solved this by using .run on my checks, you can read more about this here essentially this is the code that saved me:

// parallel processing
const validate = validations => {
  return async (req, res, next) => {
    await Promise.all(validations.map(validation => validation.run(req)));

    const errors = validationResult(req);
    if (errors.isEmpty()) {
      return next();
    }

    res.status(400).json({ errors: errors.array() });
  };
};

Related