TypeStack/class-validator for TypeScript: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course
\n

TypeStack/class-validator for TypeScript: Complete Guide with Examples

\n\n
\n

1. What It Is and Why You Need It

\n

The TypeStack/class-validator library is a powerful tool for data validation in TypeScript and JavaScript, based on decorators. It allows developers to describe validation rules directly in classes using property decorators. This makes the code more readable, self-documenting, and significantly simplifies processing incoming data, especially when working with REST APIs, forms, or any other data sources.

\n

Why do you need it? In modern web development, data comes from many sources: HTTP requests, configuration files, databases. Without reliable validation, this data can lead to runtime errors, security vulnerabilities, or simply incorrect application behavior. class-validator solves this problem by providing a declarative way to validate data. Instead of writing bulky if-else constructs, you simply add decorators to class properties, and the library automatically checks them against the specified rules.

\n

Another key advantage is tight integration with TypeScript. Decorators allow you not only to validate data but also to define its types, making the development process safer and more predictable. The library supports a wide range of built-in validators (from simple string length checks to complex regular expressions) and makes it easy to create custom validators.

\n
\n\n
\n

2. Installation

\n

To install the class-validator library and its required dependency reflect-metadata, run the following command in your project's terminal:

\n
npm install class-validator reflect-metadata
\n

After installation, make sure the following options are enabled in your tsconfig.json file for decorators to work correctly:

\n
{\n  "compilerOptions": {\n    "experimentalDecorators": true,\n    "emitDecoratorMetadata": true\n  }\n}
\n

It is also important to import reflect-metadata at the very beginning of your application (usually in the main file index.ts or app.ts):

\n
import "reflect-metadata";
\n
\n\n
\n

3. Quick Start

\n

Let's look at a minimal working example. Let's create a user class with field validation:

\n
import "reflect-metadata";\nimport { validate, IsString, IsEmail, MinLength } from "class-validator";\n\nclass User {\n    @IsString()\n    @MinLength(3, { message: "Name must be at least 3 characters long" })\n    name: string;\n\n    @IsEmail({}, { message: "Invalid email" })\n    email: string;\n\n    constructor(name: string, email: string) {\n        this.name = name;\n        this.email = email;\n    }\n}\n\nasync function main() {\n    const user = new User("Jo", "invalid-email");\n    const errors = await validate(user);\n\n    if (errors.length > 0) {\n        console.log("Validation errors:");\n        errors.forEach(error => {\n            console.log(`- ${error.property}: ${Object.values(error.constraints).join(", ")}`);\n        });\n    } else {\n        console.log("Validation passed successfully!");\n    }\n}\n\nmain();\n// Output:\n// Validation errors:\n// - name: Name must be at least 3 characters long\n// - email: Invalid email
\n

In this example, we created a User class, added decorators to its properties, and called the validate() function. It returns an array of errors if the data does not meet the rules.

\n
\n\n
\n

4. Main Methods/Functions/Class

Recommendations