</>
⌕
Junior #pipe#dto#validation#class-validator

ValidationPipe, DTO và class-validator dùng thế nào? whitelist, transform để làm gì?

⚡ Trả lời nhanh

DTO là class mô tả dữ liệu vào, gắn decorator của class-validator; ValidationPipe validate theo DTO và trả 400 nếu sai. whitelist loại field không khai báo, forbidNonWhitelisted báo lỗi thay vì loại, transform ép payload thành instance DTO và kiểu primitive.

export class CreateUserDto {
  @IsEmail() email: string;
  @IsString() @MinLength(8) password: string;
  @IsOptional() @IsInt() @Min(0) age?: number;
}

// main.ts
app.useGlobalPipes(new ValidationPipe({
  whitelist: true,            // bỏ field thừa
  forbidNonWhitelisted: true, // hoặc ném 400
  transform: true,            // plain -> instance DTO, "5" -> 5 cho @Param
}));
🃏 Ôn bằng flashcard