Decorator-based property validation for classes.
class-validator is a TypeScript library that enables property validation through decorators applied directly to class definitions. Built on top of validator.js, it provides 50+ built-in validation rules for strings, numbers, dates, emails, URLs, and custom types. The library works in both Node.js and browser environments, making it particularly popular in backend frameworks like NestJS where it serves as the foundation for automatic request validation.
The package emerged from the need to validate data transfer objects (DTOs) without writing repetitive boilerplate code. Instead of manually checking each property in controller methods, developers annotate class properties with decorators like @IsEmail(), @Length(min, max), or @IsInt(). The library handles both synchronous and asynchronous validation, supports nested object validation, and integrates tightly with class-transformer for type coercion before validation runs.
With over 6 million weekly downloads, class-validator has become the de facto standard for validation in TypeScript-first backend applications. NestJS developers use it through ValidationPipe to automatically validate incoming HTTP requests against DTO classes. TypeORM users apply the same decorators to entity classes for database-level validation. The decorator-based approach keeps validation rules colocated with data structures, reducing maintenance overhead in large codebases.
The library requires TypeScript's experimental decorator support and reflection metadata. While this adds configuration overhead, it enables a declarative validation style that scales well across teams. Custom validators can be created by implementing ValidatorConstraintInterface, allowing domain-specific rules while maintaining the decorator pattern throughout the codebase.
import { validate, IsEmail, Length, IsInt, Min, Max, ValidateNested, IsOptional } from 'class-validator';
import { Type } from 'class-transformer';
class Address {
@Length(5, 50)
street: string;
@Length(2, 2)
state: string;
}
class CreateUserDto {
@IsEmail()
email: string;
@Length(8, 100)
password: string;
@IsInt()
@Min(18)
@Max(120)
age: number;
@ValidateNested()
@Type(() => Address)
@IsOptional()
address?: Address;
}
const user = new CreateUserDto();
user.email = 'invalid-email';
user.password = 'short';
user.age = 15;
validate(user).then(errors => {
if (errors.length > 0) {
errors.forEach(error => {
console.log(`${error.property}: ${Object.values(error.constraints || {}).join(', ')}`);
});
// Output:
// email: email must be an email
// password: password must be longer than or equal to 8 characters
// age: age must not be less than 18
} else {
console.log('Validation passed');
}
});API Request Validation in NestJS: Automatically validate incoming HTTP request bodies, query parameters, and route params by applying decorators to DTO classes. NestJS ValidationPipe transforms plain JSON into class instances and validates them before reaching controller logic, rejecting invalid requests with structured error responses.
Database Entity Validation: Validate entity properties before persisting to databases in TypeORM applications. Apply decorators like @IsEmail() and @Length(5, 50) to entity classes so data integrity checks run before INSERT or UPDATE operations, catching issues at the application layer.
Form Data Processing: Validate user-submitted form data in full-stack TypeScript applications. Convert incoming FormData or JSON into typed class instances, run validation, and return field-specific error messages to the frontend, maintaining type safety across the entire validation pipeline.
Configuration Object Validation: Validate application configuration loaded from environment variables or config files at startup. Define a configuration class with decorators for required fields, numeric ranges, and URL formats, then validate during bootstrap to fail fast with clear error messages if configuration is invalid.
Microservice Message Validation: Validate message payloads in event-driven architectures where services communicate via message queues. Apply decorators to event classes to ensure incoming messages from RabbitMQ, Kafka, or Redis match expected schemas before processing, preventing downstream errors from malformed data.
npm install class-validatorpnpm add class-validatorbun add class-validator