Consider a NestJS DTO class with a property decorated by @IsEmail(). What will the validation result be if the property value is "not-an-email"?
import { IsEmail } from 'class-validator'; class UserDto { @IsEmail() email: string; } const user = new UserDto(); user.email = "not-an-email"; // Assume validation is run here
Think about what @IsEmail() checks for in the input.
The @IsEmail() decorator checks if the property value is a valid email format. If the value is not a valid email, validation fails with an error message.
Choose the correct way to use the @Length decorator from class-validator to ensure a string property has length between 5 and 10 characters.
import { Length } from 'class-validator'; class ProductDto { @Length(?, ?) name: string; }
Check the official @Length decorator signature.
The @Length decorator takes two numeric arguments: minimum length first, then maximum length. So @Length(5, 10) is correct.
Given this DTO:
class ScoreDto {
@IsNotEmpty()
score: number;
}
const dto = new ScoreDto();
dto.score = 0;
// Validation is run hereWhy does validation pass even though 0 might be considered empty?
Think about what @IsNotEmpty() actually checks internally.
@IsNotEmpty() checks if the value is not null or undefined. The number 0 is a valid value and not considered empty by this decorator.
Consider this DTO:
class CreateUserDto {
@IsDefined()
username: string;
}
const dto = new CreateUserDto();
// username is not set
// Validation is run hereWhat error message will the validator produce?
Look at the default message for @IsDefined().
The default error message for @IsDefined() is '
Choose the correct set of class-validator decorators to enforce that a property is:
- An array
- Contains only strings
- Has at least 2 items
- Is not empty
class TagsDto {
// decorators here
tags: string[];
}Remember to validate each item in the array and the array itself.
@IsArray() checks the property is an array.@ArrayMinSize(2) ensures at least 2 items.@IsString({ each: true }) validates each item is a string.@IsNotEmpty() ensures the array itself is not empty.