Sikau

NestJS · Day 6 · about 35 min

DTOs and validation

Describe incoming data once; reject bad input automatically.

Rules as code

Writing if (typeof body.price !== "number") in every handler gets old fast. In Nest you describe the body as a DTO class with validation decorators, turn on the global ValidationPipe, and bad requests get a clear 400 before your code ever runs.

class-validator + ValidationPipe

import { IsBoolean, IsInt, IsString, Length, Min } from "class-validator";

export class CreateDishDto {
  @IsString()
  @Length(2, 40)
  name: string;

  @IsInt()
  @Min(1)
  price: number;

  @IsBoolean()
  veg: boolean;
}
  • The controller declares @Body() dto: CreateDishDto; Nest validates against that type.
  • whitelist: true strips properties without rules; forbidNonWhitelisted: true rejects them (400) instead.
  • For updates, PartialType(CreateDishDto) makes every field optional with the same rules.

The rest of this lesson

  • Turning on the ValidationPipeexplain
  • What a 400 looks likeexplain
  • What happens?predict
  • Pick the decoratormatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of NestJS