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.