class-validator Cheatsheet: Useful Decorators and NestJS Validation Patterns (2025)

This is your complete reference for all major class-validator decorators, 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.

🚀 Inst…


This content originally appeared on DEV Community and was authored by Subhash Adhikari

This is your complete reference for all major class-validator decorators, 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) from class-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() from class-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 stopAtFirstError in ValidationPipe to fail fast

🔗 Resources

✅ Use this cheatsheet in every TypeScript API project using DTOs. Fast, reliable, and easy to maintain.


This content originally appeared on DEV Community and was authored by Subhash Adhikari


Print Share Comment Cite Upload Translate Updates
APA

Subhash Adhikari | Sciencx (2025-08-04T21:03:29+00:00) class-validator Cheatsheet: Useful Decorators and NestJS Validation Patterns (2025). Retrieved from https://www.scien.cx/2025/08/04/class-validator-cheatsheet-useful-decorators-and-nestjs-validation-patterns-2025/

MLA
" » class-validator Cheatsheet: Useful Decorators and NestJS Validation Patterns (2025)." Subhash Adhikari | Sciencx - Monday August 4, 2025, https://www.scien.cx/2025/08/04/class-validator-cheatsheet-useful-decorators-and-nestjs-validation-patterns-2025/
HARVARD
Subhash Adhikari | Sciencx Monday August 4, 2025 » class-validator Cheatsheet: Useful Decorators and NestJS Validation Patterns (2025)., viewed ,<https://www.scien.cx/2025/08/04/class-validator-cheatsheet-useful-decorators-and-nestjs-validation-patterns-2025/>
VANCOUVER
Subhash Adhikari | Sciencx - » class-validator Cheatsheet: Useful Decorators and NestJS Validation Patterns (2025). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/08/04/class-validator-cheatsheet-useful-decorators-and-nestjs-validation-patterns-2025/
CHICAGO
" » class-validator Cheatsheet: Useful Decorators and NestJS Validation Patterns (2025)." Subhash Adhikari | Sciencx - Accessed . https://www.scien.cx/2025/08/04/class-validator-cheatsheet-useful-decorators-and-nestjs-validation-patterns-2025/
IEEE
" » class-validator Cheatsheet: Useful Decorators and NestJS Validation Patterns (2025)." Subhash Adhikari | Sciencx [Online]. Available: https://www.scien.cx/2025/08/04/class-validator-cheatsheet-useful-decorators-and-nestjs-validation-patterns-2025/. [Accessed: ]
rf:citation
» class-validator Cheatsheet: Useful Decorators and NestJS Validation Patterns (2025) | Subhash Adhikari | Sciencx | https://www.scien.cx/2025/08/04/class-validator-cheatsheet-useful-decorators-and-nestjs-validation-patterns-2025/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.