The Validation Pipe
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 11 of 17.
Nothing checks a body yet, because types are gone when the code runs. Decorators from class-validator put rules on a DTO's fields.
export class CreateOrderDto {
@IsString()
@IsNotEmpty()
customer: string;
@IsOptional()
@IsInt()
quantity?: number;
}A pipe is a step Nest runs on a handler's arguments before the handler. app.useGlobalPipes(new ValidationPipe()) in main.ts checks every @Body() against its DTO. A body that breaks a rule never reaches your method: Nest answers 400 with a list, { "message": ["customer must be a string"], ... }. @IsOptional() skips the other rules when the field is absent.
Challenge
Easytitle: a non-empty string, at most 100 characters.done: optional, a boolean.- Register a global
ValidationPipeinsrc/main.ts. - Send
POST /taskswith{ "title": "" }, then{ "title": "Pay rent", "done": "yes" }, then a valid task.
Try it yourself
export class CreateTaskDto {
title: string;
done?: boolean;
}