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 that leverages ES stage-3 decorators to declare validation rules directly on class properties. It is the default validation engine in NestJS — when you define a DTO (Data Transfer Object) class with decorators like `@IsString()`, `@IsInt()`, or `@IsEmail()`, NestJS automatically validates incoming request bodies before they reach your controller handlers. This generator inspects your JSON sample, infers the appropriate class-validator decorator for each field, and produces a complete TypeScript class with all decorators applied. It detects email patterns and emits `@IsEmail()` instead of `@IsString()`, wraps nested objects with `@ValidateNested()` and `@Type(() => ClassName)` from class-transformer so recursive validation works, and marks null fields as optional with `@IsOptional()`. Arrays receive `@IsArray()` plus element-level validators with `{ each: true }` to validate every item in the collection.

How to Use

  1. Paste a representative JSON request body from your API specification into the input panel
  2. Click "Generate Class" to produce a fully decorated class-validator DTO
  3. Copy the output into your NestJS project and install both class-validator and class-transformer packages
  4. Use the DTO in your controller with @Body() and enable ValidationPipe in your main.ts for automatic validation
  5. Extend the generated class with additional constraints like @Min(), @Max(), @Length(), or @Matches() for business-specific rules

Why Use This Tool?

Automatically detects email-formatted strings and emits @IsEmail() — no manual annotation needed for common patterns
Nested objects receive @ValidateNested() and @Type(() => NestedClass) so deeply structured request bodies are validated recursively
Array fields get @IsArray() combined with @IsString({ each: true }) or @IsNumber({}, { each: true }) to validate every element, not just the array wrapper
Null values become optional properties with @IsOptional(), matching the common NestJS pattern where nullable fields are omitted from required validation
The generated class works as a NestJS DTO out of the box — just add it to a @Body() parameter and enable ValidationPipe
Separate import statements for class-validator and class-transformer are included, preventing "decorator not found" runtime errors

Tips & Best Practices

  • NestJS ValidationPipe with transform: true automatically converts plain JSON objects into class instances, which is required for decorators to work — without this option, validate() sees a plain object with no decorator metadata
  • Use validateOrReject() instead of validate() when you want validation failures to throw an exception automatically, reducing boilerplate error-handling code in your services
  • For conditional validation (e.g., field B is required only when field A has a certain value), add @ValidateIf((o) => o.fieldA === "value") after generation
  • class-validator decorators run on class instances, not plain objects. Always use plainToInstance() from class-transformer before calling validate() in non-NestJS contexts
  • When using with TypeORM entities, keep validation DTOs separate from your entity classes to avoid mixing persistence and validation concerns

Frequently Asked Questions

How does JSON map to class-validator decorators?

JSON strings map to @IsString() (or @IsEmail() if the value contains @ and a dot), integers map to @IsInt(), floats map to @IsNumber(), booleans map to @IsBoolean(), null values map to @IsOptional(), arrays map to @IsArray() plus an element-level validator with { each: true }, and nested objects map to @ValidateNested() with @Type(() => NestedClass).

When should I avoid using this generator?

Skip this tool if you need runtime schema generation (use Zod or JSON Schema instead), if your project does not use class-based validation (class-validator requires class instances, not plain objects), or if you are building a lightweight API without NestJS where function-based validators like Zod are more appropriate.

Why does nested object validation need @ValidateNested and @Type?

@ValidateNested() tells class-validator to recursively validate the nested object's decorators. @Type(() => NestedClass) from class-transformer tells the transformation engine to instantiate the nested class during plainToInstance(). Without both decorators, nested objects remain plain JSON and their decorators are never checked.

How do I validate an object with class-validator?

In NestJS, enable ValidationPipe in main.ts: app.useGlobalPipes(new ValidationPipe({ transform: true })). In standalone code: import { plainToInstance } from "class-transformer"; import { validate } from "class-validator"; const instance = plainToInstance(MyDto, plainObject); const errors = await validate(instance);

Can I add custom validation decorators after generation?

Absolutely. The generated class is a starting point. Add @Min(0) for non-negative numbers, @Length(1, 100) for string length bounds, @Matches(/regex/) for pattern validation, or create custom decorators with registerDecorator() for domain-specific rules like "must be a valid ISO country code".

Is my data sent to a server?

No. All decorator inference and code generation execute entirely in your browser. Your JSON data never leaves your device — no network requests, no server-side processing, and no data retention.

Real-world Examples

NestJS user registration DTO

Generate a class-validator DTO for a user registration endpoint that validates email, password, and profile data.

Input
{
  "email": "[email protected]",
  "password": "SecurePass123",
  "age": 25,
  "acceptTerms": true,
  "profile": {
    "firstName": "John",
    "lastName": "Doe"
  }
}
Output
export class ProfileEntity {
  @IsString()
  firstName: string;

  @IsString()
  lastName: string;
}

export class RootEntity {
  @IsEmail()
  email: string;

  @IsString()
  password: string;

  @IsInt()
  age: number;

  @IsBoolean()
  acceptTerms: boolean;

  @ValidateNested()
  @Type(() => ProfileEntity)
  profile: ProfileEntity;
}

Product creation DTO with array validation

Create a DTO for a product creation endpoint that validates tags array and nested category object.

Input
{
  "name": "Widget Pro",
  "price": 29.99,
  "tags": ["electronics", "gadget"],
  "category": {
    "id": 1,
    "name": "Electronics"
  },
  "description": null
}
Output
export class CategoryEntity {
  @IsInt()
  id: number;

  @IsString()
  name: string;
}

export class RootEntity {
  @IsString()
  name: string;

  @IsNumber()
  price: number;

  @IsArray()
  @IsString({ each: true })
  tags: string[];

  @ValidateNested()
  @Type(() => CategoryEntity)
  category: CategoryEntity;

  @IsOptional()
  description?: null;
}

Related Tools