DEV Community

Discussion on: A Clean Approach to Using Express Validator

Collapse
 
nedsoft profile image
Chinedu Orie • Edited

Certainly yes, I've recently made an improvement to it in my personal codes. The validator takes schema as a param. I found it cleaner and I'd update the article ASAP. Below is what it looks like:

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

const validate = (schemas)  => {
    return async (req, res, next) => {
      await Promise.all(schemas.map((schema) => schema.run(req)));

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

      const errors = result.array();
      return  res.send(errors)
    };
  }
 const exampleSchema = [
   body('foo', 'The foo field is required').notEmpty(),
   ...
];

router.post('/foos', validate(exampleSchema), fooHandler);

Enter fullscreen mode Exit fullscreen mode
Collapse
 
reak45 profile image
Reak45

This is just awesome! Thank you so much!

Thread Thread
 
nedsoft profile image
Chinedu Orie

Anytime!

Collapse
 
leblancmeneses profile image
Leblanc Meneses

How would you implement mutually exclusive properties like google maps geocoding?
can be either: address or latlng but not both

github.com/express-validator/expre...

seems oneOf is middleware not a ValidationChain[]. I'm handling it manually using a custom rule because that allows me to continue using similar "validate" middleware, although, what else are we missing by having this convenience "validate" wrapper .

Great writeup!