Validation4M+/wkMIT

class-validator

class-validator is a decorator-based validation library for TypeScript and JavaScript that uses class properties decorated with validation constraints to define

Installation

npm
npm install class-validator class-transformer
yarn
yarn add class-validator class-transformer
pnpm
pnpm add class-validator class-transformer

Import

ESM
import { IsEmail, IsString, MinLength, validate } from 'class-validator';

Quick Example

usage
import { IsEmail, IsString, MinLength, validate } from 'class-validator';

class CreateUserDto {
  @IsString()
  @MinLength(1)
  name: string;

  @IsEmail()
  email: string;
}

const dto = Object.assign(new CreateUserDto(), { name: 'Alice', email: '[email protected]' });
const errors = await validate(dto);
console.log(errors.length === 0 ? 'Valid' : errors);

About class-validator

class-validator is a decorator-based validation library for TypeScript and JavaScript that uses class properties decorated with validation constraints to define validation rules. The library integrates naturally with class-based architectures like NestJS, TypeORM, and other frameworks that use TypeScript decorators extensively. Validation decorators are applied directly to class properties: @IsString(), @IsEmail(), @MinLength(3), @MaxLength(50), @IsInt(), @Min(0), @IsOptional(), @IsArray(), @ValidateNested(), and many more. The validate() function checks a class instance against its decorators and returns an array of validation errors with property paths, constraint names, and error messages. class-validator supports custom validation decorators through @ValidatorConstraint and @Validate, conditional validation with @ValidateIf, validation groups for applying different rules in different contexts, and whitelist validation that strips undecorated properties. The library works with class-transformer for converting plain objects to class instances before validation. In NestJS, class-validator integrates through the ValidationPipe, automatically validating request bodies, query parameters, and route parameters against DTO classes. class-validator is the standard validation approach in the NestJS ecosystem and any TypeScript project using decorator-based class definitions.

Quick Facts

Packageclass-validator
CategoryValidation
Weekly Downloads4M+
LicenseMIT
Installnpm install class-validator class-transformer

Related Packages

Browse npm Packages by Category

Explore our reference of 200 popular npm packages with install commands, examples, and quick-start guides.