How to use class-validators with ValidationPipes in NestJS

Posted on Apr 13, 2022
Note: This article was written a while ago and may contain outdated information. Please verify the details before relying on it. If I express opinions or recommendations, they might not reflect my current views. For this reason, I recommend checking for more recent articles on the same topic.

If you want to validate the values of an incoming request body (like for example whether the e-mail is valid), then you can use in NestJS ValidationPipes.

This build-in feature allows you to abstract the validation away from your business logic. This makes it a good alternative to Joi.

A package which has these built-in pipes and is a recommended way to use it in NestJS is the class-validator package.

Here’s how to use it.

Using the class-validator package

First install the necessary packages:

npm i --save class-validator class-transformer

In your bootstrap() method - which is probably in the main.ts - add the following line:

app.useGlobalPipes(new ValidationPipe());

So that file looks like the following:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}

Now you can annotate the fields of your DTOs with the according validators:

import { IsEmail, IsNotEmpty } from 'class-validator';

export class RegisterDto {
  @IsEmail()
  email: string;

  @IsNotEmpty()
  password: string;
}

Setting options

With this you have enabled your application for a wide-range of available validations with customized error messages and more!

Check the Documentation and repository for more information.