A better way to do the validation in NestJS

Tushar Roy Chowdhury
Towards Dev
Published in
2 min readJan 2, 2022

--

Hello everyone!! In most cases, we need to validate the request from client-side which is very crucial sometimes. So I am going to describe a small trick to do the validation with ease. First look at the picture —

Error response

Can you guess the key-name of those values(under message property)? Sometimes it is hard to tell. isn’t it? So what if the error response will be like this (Look at the picture)?

Error response

Now you can clearly understand the error response.
So let’s jump into the code. Let’s take an example of a sign-up form & name it -signup-credentials.dto.ts

Another file is validation.filter.ts which is responsible for arranging the error response.

As we are doing the validation for all possible modules in an application, so it will be better if we keep things concise & re-usable. In that case, we are going to call this filter file from main.ts.

Now, if you do the validation you can see the organized error response.
Isn’t it awesome!!!

N.B. I have also created a simple application called Food APP. It’s a little bit of advance which has unit test & e2e test strategies. You can check — FOOD-APP

Thank you…

--

--

I am a passionate programmer and always keep eye on new technologies and scrutinize them until getting into shape.