Validation Middleware

Snippets Jun 30, 2022

A sample Express middleware for TypeScript body validation using class-transformer and class-validator

export const validateBody = (classToConvert: any) => {
  return (req: Request, res: Response, next: NextFunction) => {
    const rsdata = plainToInstance(classToConvert, req.body);
  
    validate(rsdata).then((errors) => {
      if (errors.length > 0) {
        const simplified = 
          errors.reduce((_p, c) => Object.values(c.constraints), []);

        return res.status(400).send({
          errors: simplified
        });
      }

      next();
    });
  };
};

Usage

router.post('/something', validateBody(YOUR_CLASS), async(req: Request, res: Response): Promise<Response> => {
  // TODO: Something..
 });

Use in conjunction with class-validator within your body classes for best results.

Tags

Steven

Steven has been writing software and exploring computers since the age of 17 all the way back in 2008!