0
0
NestJSframework~30 mins

class-validator decorators in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Validating User Input with class-validator Decorators in NestJS
📖 Scenario: You are building a simple user registration form in a NestJS backend. You want to ensure that the data sent by users is valid before processing it.
🎯 Goal: Create a User Data Transfer Object (DTO) class using class-validator decorators to validate user input fields like username, email, and age.
📋 What You'll Learn
Create a class called UserDto with properties username, email, and age.
Add validation decorators @IsString() and @Length(3, 20) to username.
Add validation decorators @IsEmail() to email.
Add validation decorators @IsInt(), @Min(18), and @Max(99) to age.
💡 Why This Matters
🌍 Real World
Validating user input is essential in web applications to prevent bad data and security issues. Using class-validator decorators in NestJS makes this easy and clean.
💼 Career
Backend developers working with NestJS often create DTOs with validation decorators to ensure data integrity and improve application reliability.
Progress0 / 4 steps
1
Create the UserDto class with properties
Create a class called UserDto with three properties: username of type string, email of type string, and age of type number.
NestJS
Need a hint?

Define a class with three properties and their types exactly as specified.

2
Add validation decorators for username
Import IsString and Length from class-validator. Add the decorators @IsString() and @Length(3, 20) above the username property.
NestJS
Need a hint?

Remember to import the decorators before using them.

3
Add validation decorator for email
Import IsEmail from class-validator. Add the decorator @IsEmail() above the email property.
NestJS
Need a hint?

Use @IsEmail() to check if the email is valid.

4
Add validation decorators for age
Import IsInt, Min, and Max from class-validator. Add the decorators @IsInt(), @Min(18), and @Max(99) above the age property.
NestJS
Need a hint?

Use these decorators to ensure age is an integer between 18 and 99.