Validation with Pipes
Give your DTOs runtime teeth. class-validator + class-transformer, the ValidationPipe's three critical options, @IsOptional() mechanics, and the PartialType shortcut.
Alright, you've got the skeleton. Now let's give those DTOs actual teeth instead of being glorified TypeScript interfaces pretending to do something.
The Problem You Have Right Now
Your CreateTaskDto currently looks like this:
export class CreateTaskDto {
title: string;
description: string;
}This is a compile-time lie. TypeScript types evaporate at runtime. When someone sends POST /tasks with { "title": 123, "yolo": true }, your service happily accepts it. title is now a number, description is undefined, and your "typed" DTO did absolutely nothing. You've been writing Java-shaped code with JavaScript-shaped behavior.
Analogy
A TypeScript type without runtime validation is like the packing list you wrote at home before a trip: it helped you think, but nobody at the border ever reads it. What crosses the border is whatever is actually in the suitcase. Validation is the customs officer who opens it.
The Two Packages That Fix This
npm install class-validator class-transformerclass-validator — Provides decorators (@IsString(), @IsNotEmpty(), @IsBoolean(), etc.) that define validation rules on class properties. These decorators attach metadata to the class at runtime.
class-transformer — Converts plain JSON objects (what Express gives you from req.body) into actual class instances. This is critical because decorators only exist on class instances, not on plain objects. Without transformation, there's nothing to validate against.
Why both? Think of it this way: - class-transformer: turns {} into new CreateTaskDto() - class-validator: reads decorators on that instance and checks if values comply
One without the other is useless.
Analogy
Think of an arrival at the airport: class-transformer is the desk that takes your loose handful of papers and staples them into the official landing form, and class-validator is the officer who can only stamp official forms. Hand the officer loose papers and there is nothing to stamp; fill in the form but never queue for the officer and nobody checks it. It takes both to get through.
ValidationPipe — The Orchestrator
NestJS ships a built-in ValidationPipe that wires both packages together. Here's what it does internally, step by step:
plainToInstance(CreateTaskDto, body) — converts the plain object → an
actual CreateTaskDto class instance
validate(dtoInstance) — reads all decorators on the instance's
properties and checks every rule — @IsString(), @IsNotEmpty(),
@MinLength(), etc.
controller receives the validated, typed DTO instance
ValidationPipe throws BadRequestException (400) with detailed error
messages — never reaches your controller
Analogy
The ValidationPipe is passport control at the border of your application. Every traveler (request body) is processed the same way — papers converted to the official form, every rule checked — before they're allowed into the country where your controllers live. Travelers who fail are turned around at the desk with a written list of reasons; they never set foot inside.
Your controller code doesn't change at all. The pipe runs in the pipeline before the controller method executes. Remember the lifecycle?
Request → Middleware → Guards → Interceptors → ④ PIPES → Controller
▲
ValidationPipe lives hereEnabling ValidationPipe Globally
You can apply it per-route, per-controller, or globally. Global is what you want 99% of the time. Do it once, forget about it.
main.ts — One line added
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
await app.listen(3000);
}
bootstrap();Those three options — understand each one:
whitelist: true Strips any property that does NOT have a decorator in the DTO. Client sends { "title": "test", "hackField": "malicious" }? hackField gets silently removed before it reaches your controller. Gone. This is security 101.
forbidNonWhitelisted: true Takes whitelist one step further. Instead of silently stripping unknown properties, it throws a 400 error. You're telling the client: "Don't send me garbage I didn't ask for." Use this in development to train your frontend devs to not send random fields. In production, you might switch to just whitelist: true (silent strip) depending on how forgiving you want to be.
transform: true Enables class-transformer auto-transformation. Without this, @Body() gives you a plain object even though TypeScript thinks it's a CreateTaskDto. With this, you get an actual instance of the class. It also coerces DTO body properties to their declared types.
The @Param('id') coercion caveat
You'll often hear "with transform: true you can drop ParseIntPipe." It's only partly true. Auto-converting a bare route param (@Param('id') id: number) from its TypeScript type relies on implicit conversion, which is off by default. To get it, you must opt in:
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: { enableImplicitConversion: true }, // ← needed for bare params
});Even then, enableImplicitConversion is a blunt instrument (it can mis-coerce in surprising ways). The explicit @Param('id', ParseIntPipe) is clearer, self-documenting, and gives a clean 400 on "abc" — so this course keeps it. Reach for implicit conversion only when you understand the trade-off.
Analogy
The three options are three customs policies. whitelist quietly confiscates anything not on the declaration form. forbidNonWhitelisted doesn't just confiscate — it fines you for trying. And transform is the currency exchange at the border: whatever you arrive with gets converted into the local denomination before you're let through.
Updated DTOs with Validation Decorators
create-task.dto.ts
import { IsString, IsNotEmpty, MaxLength } from 'class-validator';
export class CreateTaskDto {
@IsString({ message: 'title must be a string, not whatever you just sent' })
@IsNotEmpty({ message: 'title should not be empty — what kind of task has no title?' })
@MaxLength(100)
title: string;
@IsString()
@IsNotEmpty()
@MaxLength(500)
description: string;
}update-task.dto.ts
import { IsString, IsBoolean, IsOptional, MaxLength } from 'class-validator';
export class UpdateTaskDto {
@IsOptional()
@IsString()
@MaxLength(100)
title?: string;
@IsOptional()
@IsString()
@MaxLength(500)
description?: string;
@IsOptional()
@IsBoolean()
done?: boolean;
}Key decorator explanations:
| Decorator | What it does |
|---|---|
@IsString() | Fails if value is not a string. 123 → rejected. |
@IsNotEmpty() | Fails on "", null, undefined. Catches empty strings that @IsString() alone won't. |
@IsBoolean() | Only accepts true or false. Not "true", not 1. Actual booleans. |
@IsOptional() | If the field is missing/undefined, skip all other validators on this property. Without this on optional fields, @IsString() would scream when the field isn't sent. Order matters — put @IsOptional() first. |
@MaxLength(n) | String can't exceed n characters. |
{ message: '...' } | Custom error message override. Every decorator accepts this. |
What Happens Now — Traced
Happy path: POST /tasks with { "title": "Learn NestJS", "description": "Validation chapter" }
→ CreateTaskDto { title: "Learn NestJS", description: "Validation chapter" }
→ @IsString() on title ✓ (it's a string)
→ @IsNotEmpty() on title ✓ (not empty)
→ @MaxLength(100) on title ✓ (11 chars)
→ @IsString() on description ✓
→ @IsNotEmpty() on description ✓
→ @MaxLength(500) on description ✓
Sad path: POST /tasks with { "title": "", "description": 42, "hackField": "gotcha" }
→ "hackField" has no decorator in CreateTaskDto
→ REJECTED immediately: "property hackField should not exist"
(even if hackField wasn't there, validation continues…)
→ @IsNotEmpty() on title ✗ — empty string
→ @IsString() on description ✗ — 42 is not a string
The 400 response the client gets:
{
"statusCode": 400,
"message": [
"property hackField should not exist",
"title should not be empty — what kind of task has no title?",
"description must be a string"
],
"error": "Bad Request"
}That array of messages — each failed decorator produces one. The client gets ALL validation errors at once, not one at a time. No back-and-forth fixing one field per request.
The Update DTO and @IsOptional() Flow
PATCH /tasks/1 with { "done": true }
Only done is sent. What happens to title and description?
title and description are undefined
Validating title:
→ @IsOptional() sees title is undefined → SKIP all other decorators on
title ✓
Validating description:
→ @IsOptional() sees description is undefined → SKIP ✓
Validating done:
→ @IsOptional() sees done is present → continue checking
→ @IsBoolean() → true is a boolean ✓
Object.assign(task, { done: true }) — only done gets updated
Without @IsOptional(), sending a partial update would fail because @IsString() on title would reject undefined. This is why decorator order and @IsOptional() placement matter.
Analogy
@IsOptional() is the "nothing to declare" lane. If you're not carrying the item at all, you walk straight past every check for it. But the moment you do carry it, you're back in the regular lane and every rule applies in full.
Bonus: The PartialType Shortcut You'll Actually Want
Right now your UpdateTaskDto manually duplicates fields from CreateTaskDto with @IsOptional() added. That's fine for 2 fields. It's maintenance hell for 15 fields. NestJS has a utility:
npm install @nestjs/mapped-typesimport { PartialType } from '@nestjs/mapped-types';
import { CreateTaskDto } from './create-task.dto';
export class UpdateTaskDto extends PartialType(CreateTaskDto) {
@IsOptional()
@IsBoolean()
done?: boolean;
}PartialType(CreateTaskDto) takes every property from CreateTaskDto, keeps all their validation decorators, and wraps each one with @IsOptional(). Then you just add the extra done field that only exists in updates. DRY, no duplication, decorators inherited automatically.
Analogy
PartialType is the visa renewal form. It's photocopied from the original application — same fields, same rules — except every field is stamped "only if it changed". You'd never retype the whole application by hand just to make each line optional; you reuse the original and let the copier do it.
Controller — Nothing Changes
@Post()
create(@Body() createTaskDto: CreateTaskDto): Task {
// by the time this runs, createTaskDto is GUARANTEED to be valid
// ValidationPipe already threw 400 if it wasn't
return this.tasksService.create(createTaskDto);
}Your controller stays thin. It doesn't know validation exists. It just trusts that whatever arrives has already been validated. That's the beauty of the pipe architecture — separation of concerns enforced by the framework, not by your discipline.
Analogy
Once you're past the border, nobody in the city asks for your passport again. Shops, hotels, and offices (your controllers and services) simply trust that everyone walking around was checked at entry. That's what one well-guarded checkpoint buys you: the entire interior stays simple.
Common Decorators You'll Use Often
| Decorator | Use case |
|---|---|
@IsEmail() | Email format validation |
@IsEnum(SomeEnum) | Must be one of enum values |
@IsArray() | Must be an array |
@ArrayMinSize(1) | Array can't be empty |
@IsInt() | Integer only, no floats |
@Min(0) / @Max(100) | Number range |
@Matches(/regex/) | Regex pattern matching |
@ValidateNested() | Validate nested objects (used with @Type() from class-transformer) |
@IsDateString() | ISO 8601 date string |
You can also write custom validators when built-in ones don't cover your case — but that's a later topic.
Quick Recap of What You've Added
Before: Request → Controller → Service (pray the data is correct)
After: Request → ValidationPipe → [transform → validate → reject/pass] → Controller → ServiceThree things changed: installed 2 packages, added 3 lines to main.ts, and put decorators on DTO properties. Your controller and service code? Untouched. That's what a good architectural layer looks like — it slots in without disturbing what already works.
Next logical step when you're ready: Exception Filters — controlling exactly what error responses look like instead of relying on NestJS defaults.
