How to Use class-validator in NestJS for Input Validation
In NestJS, use
class-validator by defining DTO classes with validation decorators like @IsString() and @IsNotEmpty(). Then apply the ValidationPipe globally or in controllers to automatically validate incoming requests.Syntax
To use class-validator in NestJS, create a Data Transfer Object (DTO) class and decorate its properties with validation decorators. Then use ValidationPipe to trigger validation.
@IsString(): Checks if a value is a string.@IsNotEmpty(): Ensures the value is not empty.ValidationPipe: A NestJS pipe that validates incoming requests against the DTO.
typescript
import { IsString, IsNotEmpty } from 'class-validator'; export class CreateUserDto { @IsString() @IsNotEmpty() name: string; @IsString() email: string; } // In controller or main.ts import { ValidationPipe } from '@nestjs/common'; // Apply globally app.useGlobalPipes(new ValidationPipe());
Example
This example shows a simple NestJS controller using class-validator to validate a user creation request. If validation fails, NestJS returns a 400 error with details.
typescript
import { Controller, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common'; import { IsString, IsNotEmpty, IsEmail } from 'class-validator'; class CreateUserDto { @IsString() @IsNotEmpty() name: string; @IsEmail() email: string; } @Controller('users') export class UsersController { @Post() @UsePipes(new ValidationPipe()) createUser(@Body() createUserDto: CreateUserDto) { return { message: 'User created', user: createUserDto }; } }
Output
POST /users with body {"name":"Alice","email":"alice@example.com"} returns 201 {"message":"User created","user":{"name":"Alice","email":"alice@example.com"}}
POST /users with body {"name":"","email":"not-an-email"} returns 400 with validation error details
Common Pitfalls
Common mistakes when using class-validator in NestJS include:
- Not applying
ValidationPipe, so validation never runs. - Forgetting to decorate DTO properties, so no validation rules apply.
- Using plain objects instead of DTO classes, which disables validation.
- Not enabling
whitelistinValidationPipeto strip unwanted properties.
typescript
/* Wrong: No ValidationPipe applied, validation ignored */ @Post() createUser(@Body() createUserDto: CreateUserDto) { return createUserDto; } /* Right: Use ValidationPipe to validate */ @Post() @UsePipes(new ValidationPipe({ whitelist: true })) createUser(@Body() createUserDto: CreateUserDto) { return createUserDto; }
Quick Reference
Summary tips for using class-validator in NestJS:
- Define DTO classes with decorators like
@IsString(),@IsEmail(),@IsNotEmpty(). - Apply
ValidationPipeglobally inmain.tsor per route. - Enable
whitelist: trueinValidationPipeto remove unexpected fields. - Use
transform: trueinValidationPipeto auto-transform payloads to DTO instances.
Key Takeaways
Use class-validator decorators on DTO classes to define validation rules.
Apply ValidationPipe in NestJS to automatically validate incoming requests.
Enable whitelist and transform options in ValidationPipe for safer and cleaner data.
Always use DTO classes, not plain objects, for validation to work.
Validation errors return HTTP 400 with detailed messages by default.