Zum Inhalt springen

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.

🚀 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.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert