Discover how a few simple tags can save you hours of debugging and keep your data safe!
Why class-validator decorators in NestJS? - Purpose & Use Cases
Imagine building a form where users enter their data, and you have to check every field manually to make sure it is correct before saving it.
Manually checking each input is slow, easy to forget, and can lead to bugs if you miss a rule or write inconsistent checks.
class-validator decorators let you add simple tags to your data classes that automatically check if the data is valid, keeping your code clean and reliable.
if (!email.includes('@')) { throw new Error('Invalid email'); }
@IsEmail() email: string;
You can easily enforce rules on your data with clear, reusable, and automatic validation.
When a user signs up, class-validator decorators check their email and password format before saving, preventing bad data from entering your system.
Manual validation is error-prone and repetitive.
class-validator decorators simplify and automate data checks.
This leads to cleaner code and fewer bugs.
Practice
@IsEmail() decorator in class-validator when used in a NestJS DTO class?Solution
Step 1: Understand the decorator's role
The@IsEmail()decorator validates that the decorated property contains a valid email format string.Step 2: Compare options with decorator behavior
Only To check if the property value is a valid email address format matches the validation purpose of@IsEmail(). Other options describe unrelated behaviors.Final Answer:
To check if the property value is a valid email address format -> Option BQuick Check:
@IsEmail()validates email format [OK]
- Thinking @IsEmail() modifies the value instead of validating
- Confusing @IsEmail() with @IsOptional() or @Transform decorators
@Length() decorator to require a string property to be between 5 and 10 characters in NestJS?Solution
Step 1: Recall the syntax of @Length decorator
The@Length()decorator takes two numeric arguments: minimum length first, then maximum length.Step 2: Match options with correct syntax
@Length(5, 10) correctly uses@Length(5, 10). Options A, B, and D use incorrect argument order or syntax.Final Answer:
@Length(5, 10) -> Option AQuick Check:
@Length(min, max) = @Length(5, 10) [OK]
- Swapping min and max values
- Using object syntax instead of positional arguments
- Using named parameters which are invalid
username = 'abc' and age = 17?
class UserDto {
@Length(5, 15)
username: string;
@Min(18)
age: number;
}Solution
Step 1: Check username length
The username 'abc' has length 3, which is less than the minimum 5 required by@Length(5, 15). So username is invalid.Step 2: Check age minimum
The age is 17, which is less than the minimum 18 required by@Min(18). So age is invalid.Final Answer:
Validation fails because both username and age are invalid -> Option DQuick Check:
username too short + age too low = both invalid [OK]
- Ignoring one invalid field and assuming validation passes
- Confusing @Min with @Max for age
- Assuming length includes spaces or trimming automatically
class-validator decorators:
class ProductDto {
@IsInt()
@Min(1)
price: string;
}Solution
Step 1: Analyze property type and decorators
The propertypriceis declared asstring, but decorators@IsInt()and@Min(1)expect a number type.Step 2: Identify mismatch causing validation error
Sincepriceis string, validation will fail because@IsInt()requires a number. The type should benumber.Final Answer:
price should be a number type, not string -> Option AQuick Check:
Type mismatch between property and decorators = error [OK]
- Using string type with number validators
- Assuming decorators convert types automatically
- Ignoring TypeScript type declarations
tags which is an array of strings, each string must be at least 3 characters. Which combination of class-validator decorators correctly enforces this?Solution
Step 1: Validate the property is an array
Use@IsArray()to ensuretagsis an array type.Step 2: Validate each element is a string with length constraints
Use@IsString({ each: true })and@Length(3, 50, { each: true })to apply string and length validation to every item in the array.Step 3: Ensure array has at least one element
@ArrayMinSize(1)ensures the array is not empty.Final Answer:
@IsArray()\n@ArrayMinSize(1)\n@IsString({ each: true })\n@Length(3, 50, { each: true }) -> Option CQuick Check:
Array + each:true for element validation = @IsArray()\n@ArrayMinSize(1)\n@IsString({ each: true })\n@Length(3, 50, { each: true }) [OK]
- Forgetting { each: true } for array element validation
- Using @IsString() without array context
- Setting wrong array size constraints
Ready to prove it?
Pass the test and this pattern moves unknown
