Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 36 of 56 · Typescript

Validation with `class-validator` & Decorators

Duration: 20 minutes

Install

npm i class-validator class-transformer reflect-metadata
npm i -D @types/class-validator

Add import 'reflect-metadata'; at the entry point.

DTO with decorators

import { IsInt, IsString, Length, validate } from 'class-validator';

export class CreateUserDto {
  @IsString()
  @Length(2, 20)
  name!: string;

  @IsInt()
  age!: number;
}

async function validateInput(input: any) {
  const dto = Object.assign(new CreateUserDto(), input);
  const errors = await validate(dto);
  if (errors.length) throw new Error('Invalid');
  return dto;
}

Use this in an Express route to enforce runtime validation while keeping compile‑time types.

Info

class-validator works best with class‑based DTOs; keep them separate from ORM entities for clarity.

Previous: Express Server Typed with TypeScriptNext: Database Access with TypeORM