0
0
NestjsHow-ToBeginner ยท 4 min read

How to Validate Request in NestJS: Simple Guide

In NestJS, you validate requests by using DTOs (Data Transfer Objects) with class-validator decorators and applying the ValidationPipe globally or at the controller level. This setup automatically checks incoming data and returns errors if validation fails.
๐Ÿ“

Syntax

To validate requests in NestJS, you create a DTO class with validation decorators from class-validator. Then, you apply the ValidationPipe to your controller or globally in your app.

  • @IsString(), @IsInt(), etc. decorate DTO properties to define rules.
  • ValidationPipe checks incoming data against these rules.
  • Use @Body() to bind request body to the DTO.
typescript
import { IsString, IsInt, MinLength } from 'class-validator';
import { ValidationPipe, Post, Body } from '@nestjs/common';

export class CreateUserDto {
  @IsString()
  @MinLength(3)
  name: string;

  @IsInt()
  age: number;
}

// In controller
@Post()
create(@Body(new ValidationPipe()) createUserDto: CreateUserDto) {
  // your logic
}
๐Ÿ’ป

Example

This example shows a simple NestJS controller that validates a user creation request. The CreateUserDto class defines rules for name and age. The ValidationPipe automatically checks the request body and returns an error if validation fails.

typescript
import { Controller, Post, Body, ValidationPipe } from '@nestjs/common';
import { IsString, IsInt, MinLength, Min } from 'class-validator';

class CreateUserDto {
  @IsString()
  @MinLength(3)
  name: string;

  @IsInt()
  @Min(0)
  age: number;
}

@Controller('users')
export class UsersController {
  @Post()
  createUser(@Body(new ValidationPipe()) createUserDto: CreateUserDto) {
    return { message: 'User created', user: createUserDto };
  }
}
Output
POST /users with body {"name":"Jo","age":25} returns 400 Bad Request with validation error for name length POST /users with body {"name":"John","age":25} returns 200 OK with {"message":"User created","user":{"name":"John","age":25}}
โš ๏ธ

Common Pitfalls

Common mistakes when validating requests in NestJS include:

  • Not enabling ValidationPipe globally or on routes, so validation does not run.
  • Forgetting to use DTO classes and decorators, leading to no validation.
  • Not transforming payloads to DTO instances by missing transform: true option in ValidationPipe, causing type mismatches.
  • Using incorrect decorators or missing required fields.
typescript
/* Wrong: No ValidationPipe applied, no validation happens */
@Post()
createUser(@Body() createUserDto: CreateUserDto) {
  return createUserDto; // No validation error even if data is wrong
}

/* Right: Apply ValidationPipe with transform option */
@Post()
createUser(@Body(new ValidationPipe({ transform: true })) createUserDto: CreateUserDto) {
  return createUserDto; // Validated and transformed
}
๐Ÿ“Š

Quick Reference

Summary tips for request validation in NestJS:

  • Use class-validator decorators in DTO classes.
  • Apply ValidationPipe globally in main.ts with app.useGlobalPipes(new ValidationPipe({ transform: true })) for best practice.
  • Always use @Body() with DTO types in controllers.
  • Check validation errors returned as 400 Bad Request automatically.
โœ…

Key Takeaways

Use DTO classes with class-validator decorators to define validation rules.
Apply ValidationPipe globally or on routes to enable automatic validation.
Enable transform option in ValidationPipe to convert plain objects to DTO instances.
Validation errors automatically return 400 responses with details.
Always bind request data to DTOs using @Body() for validation to work.