This is your complete reference for all major
class-validatordecorators, their usage, value types, and integration patterns. Bookmark this if youβre working with DTOs in NestJS or doing input validation in any TypeScript project.
π Install First
npm install class-validator class-transformer β Basic Usage Pattern
import { IsEmail, MinLength, validate } from 'class-validator'; class LoginDto { @IsEmail() email: string; @MinLength(6) password: string; } const login = new LoginDto(); login.email = 'invalid'; login.password = '123'; const errors = await validate(login); π§Ύ Core Decorators Reference
| Decorator | Purpose | Accepted Type(s) |
|---|---|---|
@IsString() | Must be a string | string |
@IsBoolean() | Must be boolean | boolean |
@IsInt() | Must be an integer | number |
@IsNumber() | Any number (int or float) | number |
@IsEmail() | Valid email address | string |
@IsDate() | Must be a Date instance | Date |
@IsOptional() | Skip validation if undefined/null | any |
@IsNotEmpty() | Not empty (works with string, array) | string, array |
@IsDefined() | Value must be present (not undefined) | any |
π’ Number Validations
| Decorator | Description |
|---|---|
@Min(value) | Minimum number allowed |
@Max(value) | Maximum number allowed |
@IsPositive() | Must be positive |
@IsNegative() | Must be negative |
π String Validations
| Decorator | Description |
|---|---|
@MinLength(n) | Minimum string length |
@MaxLength(n) | Maximum string length |
@Matches(regex) | Must match regex pattern |
@IsAlpha() | Only letters |
@IsAlphanumeric() | Letters and numbers only |
@IsPhoneNumber() | Must be a valid phone number |
@IsUrl() | Must be a valid URL |
π Array Validations
| Decorator | Description |
|---|---|
@IsArray() | Must be an array |
@ArrayMinSize(n) | Minimum length of array |
@ArrayMaxSize(n) | Maximum length of array |
@ArrayNotEmpty() | Must not be empty |
@IsInt({ each: true }) | Validates each element (works with many) |
π Enum & Object Validations
enum Role { USER = 'user', ADMIN = 'admin' } @IsEnum(Role) role: Role; @ValidateNested() @Type(() => Profile) profile: Profile; -
@ValidateNested()is required for nested objects - Must be combined with
@Type(() => ClassName)fromclass-transformer
βοΈ Conditional Validation
@ValidateIf(o => o.isAdult) @IsString() licenseNumber: string; Use @ValidateIf() to apply a rule conditionally based on other values.
π Custom Validators
@ValidatorConstraint({ name: 'IsStrongPassword', async: false }) class IsStrongPassword implements ValidatorConstraintInterface { validate(value: string) { return typeof value === 'string' && value.length >= 8 && /[A-Z]/.test(value); } defaultMessage() { return 'Password must be at least 8 chars and include an uppercase letter.'; } } Use it like this:
@Validate(IsStrongPassword) password: string; βοΈ NestJS Global Integration
// main.ts app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true, transformOptions: { enableImplicitConversion: true } })); π§ Common Mistakes to Avoid
- β Forgetting
@Type(): Nested validation wonβt work without it - β Validating plain objects: Use
plainToInstance()fromclass-transformer - β Wrong order of decorators: Execution is bottom-to-top, so arrange carefully
π¦ Pro Tips
- Combine
@IsOptional()with other validators to skip when empty - Use
{ each: true }to apply decorators to every array element - Custom validators = reusable logic for business rules
- Enable
stopAtFirstErrorinValidationPipeto fail fast
π Resources
- π class-validator GitHub
- π class-transformer Docs
- π Full Guide Blog (Long-Form)
- π Connect on LinkedIn
β Use this cheatsheet in every TypeScript API project using DTOs. Fast, reliable, and easy to maintain.
Top comments (0)