0
0
NestjsHow-ToBeginner ยท 4 min read

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 whitelist in ValidationPipe to 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 ValidationPipe globally in main.ts or per route.
  • Enable whitelist: true in ValidationPipe to remove unexpected fields.
  • Use transform: true in ValidationPipe to 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.