JSON to class-validator Generator

Convert JSON to TypeScript classes with class-validator decorators for NestJS and TypeORM

class-validator class will appear here...

What is JSON to class-validator Generator?

class-validator is a decorator-based validation library for TypeScript classes, commonly used with TypeORM, NestJS, and other frameworks. It uses ES decorators to define validation rules on class properties. This tool automatically generates TypeScript classes with appropriate decorators from JSON samples, ready for use in your application.

How to Use

  1. Paste your JSON into the left panel.
  2. Click "Generate" to produce the class-validator decorated class.
  3. Copy the output and paste it into your TypeScript project.
  4. Install dependencies: npm install class-validator class-transformer
  5. Use with validate(instance) or in NestJS DTOs.

Why Use This Tool?

Generates @IsString, @IsNumber, @IsInt, @IsBoolean, @IsEmail decorators
Detects email patterns automatically and uses @IsEmail()
Handles nested objects with @ValidateNested and @Type decorators
Arrays get @IsArray with appropriate { each: true } validators
Null values become optional properties with @IsOptional()

Tips & Best Practices

  • class-validator works with class-transformer for plain-to-class conversion
  • Use validate(object) to get validation errors, or validateOrReject to throw
  • For NestJS, use these as DTOs in controllers with @Body()
  • Add custom validators like @Min(), @Max(), @Length() for additional constraints
  • Enable transform in NestJS ValidationPipe for automatic type conversion

Frequently Asked Questions

What is class-validator used for?

class-validator is primarily used in NestJS applications for validating request DTOs, with TypeORM for entity validation, and in any TypeScript project that needs decorator-based validation. It integrates well with class-transformer for converting plain objects to class instances.

How do I validate an object with class-validator?

First convert plain object to class: import { plainToInstance } from "class-transformer"; const instance = plainToInstance(MyClass, plainObject). Then validate: import { validate } from "class-validator"; const errors = await validate(instance). If errors.length === 0, validation passed.

Why are nested objects handled differently?

Nested objects require @ValidateNested() decorator to enable recursive validation, and @Type(() => NestedClass) from class-transformer to properly instantiate the nested class during transformation. Without these, nested objects would be validated as plain objects without decorator checks.

Related Tools