Skip to content

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

  1. Install Required Packages

    Terminal window
    npm i --save class-validator class-transformer
  2. 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;
    }
  3. Apply Validation in Controllers

    users.controller.ts
    @Controller('users')
    export class UsersController {
    @Post()
    create(@Body() body: UserDto) {
    // your logic to handle the user creation
    return 'User created successfully';
    }
    }

    The @Body() body: UserDto creates a variable body and assign all body data in to the variable. We can access the data’s like , body.email ,body.age

  4. 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 pipe
    app.useGlobalPipes(new ValidationPipe({
    transform: true, // Automatically transform payload into DTO instances
    whitelist: true, // Strip properties that do not exist in the DTO
    forbidNonWhitelisted: true, // Throw an error if non-whitelisted properties are found
    disableErrorMessages: false, // Optionally disable detailed error messages in production
    }));
    await app.listen(process.env.PORT ?? 3001);
    }
    bootstrap();