TypeStack/class-validator for TypeScript: Complete Guide with Examples
\n\n1. What It Is and Why You Need It
\nThe 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.
\nWhy 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.
\nAnother 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.
\n2. Installation
\nTo install the class-validator library and its required dependency reflect-metadata, run the following command in your project's terminal:
\nnpm 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 "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):
import "reflect-metadata";\n 3. Quick Start
\nLet's look at a minimal working example. Let's create a user class with field validation:
\nimport "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.
4. Main Methods/Functions/Class
Also in library
Geolocation and Maps in Java: Libraries, API and Code Examples
Java Standard Library: A Complete Overview for Beginners and Pros
Internationalization (i18n) in Swift for iOS and macOS