Class validator
In NestJS, class-validator is a popular library used for validating incoming data, typically in request bodies, query parameters, or route parameters. It works in conjunction with class-transformer to allow automatic transformation of plain objects into instances of a class, while also validating their properties.
Why Use class-validator in NestJS?
Validation is an essential part of building robust applications. In NestJS, you can use class-validator to enforce rules on incoming request data, ensuring that the data is of the expected type, format, or structure before passing it to your business logic.
How to Use class-validator in NestJS
-
Install Required Packages
Terminal window npm i --save class-validator class-transformer -
Create a DTO (Data Transfer Object)
DTOs are used to define the shape of the data your application expects in a request (body, query, or params). You can use class-validator decorators to apply validation rules.usersRequest.dto.ts import { IsString, IsInt, Min, IsEmail } from 'class-validator';export class UserDto {@IsString()@IsEmail()email: string;@IsString()username: string;@IsInt()@Min(18)age: number;} -
Apply Validation in Controllers
users.controller.ts @Controller('users')export class UsersController {@Post()create(@Body() body: UserDto) {// your logic to handle the user creationreturn 'User created successfully';}}The
@Body() body: UserDtocreates a variablebodyand assign all body data in to the variable. We can access the data’s like ,body.email,body.age… -
Enable Global Validation Pipe
NestJS provides a ValidationPipe that automatically validates incoming requests and transforms them into class instances. By enabling it globally, you ensure that all requests are validated against their respective DTOs without needing to manually validate each controller method.main.ts import { NestFactory } from '@nestjs/core';import { AppModule } from './app.module';async function bootstrap() {const app = await NestFactory.create(AppModule);// Enable global validation pipeapp.useGlobalPipes(new ValidationPipe({transform: true, // Automatically transform payload into DTO instanceswhitelist: true, // Strip properties that do not exist in the DTOforbidNonWhitelisted: true, // Throw an error if non-whitelisted properties are founddisableErrorMessages: false, // Optionally disable detailed error messages in production}));await app.listen(process.env.PORT ?? 3001);}bootstrap();