A Clean Approach for Validations Using Inversify & Express Validator | Part I

Tuğba Mert
3 min readMar 2, 2023
Photo by Enot Poloskun on IStock

Validations are must have for public APIs. Validations aim to detect invalid or mistaken user inputs and also to prevent from malicious attacks.

There are many ways to accomplish this; such as creating custom middleware layers or validating in the function it’s required, etc. However, these approaches are hard to follow by next developer, and all these extra validation layers create lots of spaghetti code.

We work on an API which accepts public requests. In this API we applied validations to decrease invalid inputs. The custom messages on validations help to decrease invalid retries. Those validations needed to be combined by multiple rules and apply some extra custom ones. This API is written on NodeJS combined with express server and inversify framework. With this specific setup, we needed to add some extra validations to the existing code. While implementing the task, I and my colleague encountered the express-validator library written for express servers. It‘s the closest approach to the annotation validation for typescript. We decided to try it and integrated to the some of our endpoints. Flexibility and extendibility has been everything we look for.

The library itself has built-in functions for most of the common validation requirements. If not enough it…

--

--