0
0
NestJSframework~30 mins

Nested DTO validation in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Nested DTO Validation in NestJS
📖 Scenario: You are building a simple API for a bookstore. Each book has a title and an author. The author itself has a name and an email. You want to make sure that when someone sends data to create a book, both the book and the author data are checked carefully.
🎯 Goal: Create nested DTO classes for Book and Author with validation rules. Then use these DTOs in a controller to validate incoming data automatically.
📋 What You'll Learn
Create a DTO class called AuthorDto with name and email properties.
Add validation decorators to AuthorDto: name must be a non-empty string, email must be a valid email.
Create a DTO class called BookDto with title and author properties.
Add validation decorators to BookDto: title must be a non-empty string, author must be a nested AuthorDto.
Use @ValidateNested() and @Type(() => AuthorDto) decorators to enable nested validation.
Create a simple controller method that accepts BookDto and validates the input automatically.
💡 Why This Matters
🌍 Real World
APIs often receive complex data with nested objects. Validating nested DTOs ensures data integrity and prevents errors early.
💼 Career
Backend developers use nested DTO validation in NestJS to build robust APIs that handle complex data safely and clearly.
Progress0 / 4 steps
1
Create the AuthorDto class with properties
Create a class called AuthorDto with two properties: name and email. Both should be strings.
NestJS
Need a hint?

Define a class with two string properties named exactly name and email.

2
Add validation decorators to AuthorDto
Add @IsString() and @IsNotEmpty() decorators to name, and @IsEmail() decorator to email in the AuthorDto class. Import these decorators from class-validator.
NestJS
Need a hint?

Use @IsString() and @IsNotEmpty() on name, and @IsEmail() on email.

3
Create BookDto with nested AuthorDto and validation
Create a class called BookDto with a title property as a non-empty string and an author property of type AuthorDto. Use @IsString() and @IsNotEmpty() on title. Use @ValidateNested() and @Type(() => AuthorDto) on author. Import ValidateNested from class-validator and Type from class-transformer.
NestJS
Need a hint?

Use @ValidateNested() and @Type(() => AuthorDto) on the author property to enable nested validation.

4
Use BookDto in a controller method with validation pipe
Create a NestJS controller class called BooksController with a createBook method. This method should accept a BookDto parameter decorated with @Body() and use ValidationPipe to validate the input automatically. Import necessary decorators and pipes from @nestjs/common.
NestJS
Need a hint?

Use @Body(new ValidationPipe()) to validate the incoming BookDto automatically.