0
0
NestJSframework~5 mins

class-validator decorators in NestJS

Choose your learning style9 modes available
Introduction

Class-validator decorators help you check if data is correct before using it. They make sure your app gets good information.

When you want to check user input in forms to avoid mistakes.
When receiving data from an API and you need to confirm it is valid.
When saving data to a database and want to prevent wrong values.
When building a signup or login system to verify user details.
When you want to give clear error messages if data is wrong.
Syntax
NestJS
import { IsString, IsInt, Min, Max, IsEmail } from 'class-validator';

class User {
  @IsString()
  name: string;

  @IsInt()
  @Min(0)
  @Max(120)
  age: number;

  @IsEmail()
  email: string;
}

Decorators start with @ and go above the property they check.

You can combine many decorators on one property to add multiple rules.

Examples
This checks that the title is not empty.
NestJS
import { IsNotEmpty } from 'class-validator';

class Product {
  @IsNotEmpty()
  title: string;
}
This ensures darkMode is true or false only.
NestJS
import { IsBoolean } from 'class-validator';

class Settings {
  @IsBoolean()
  darkMode: boolean;
}
This checks the password length is between 8 and 20 characters.
NestJS
import { Length } from 'class-validator';

class Password {
  @Length(8, 20)
  password: string;
}
Sample Program

This example creates a User with wrong data. It runs validation and prints errors for each wrong property.

NestJS
import { IsString, IsNotEmpty, IsInt, Min, IsEmail, validate } from 'class-validator';

class User {
  @IsString()
  @IsNotEmpty()
  name: string;

  @IsInt()
  @Min(18)
  age: number;

  @IsEmail()
  email: string;
}

async function run() {
  const user = new User();
  user.name = '';
  user.age = 15;
  user.email = 'not-an-email';

  const errors = await validate(user);
  if (errors.length > 0) {
    console.log('Validation failed. Errors:');
    errors.forEach(err => console.log(err.property + ': ' + Object.values(err.constraints).join(', ')));
  } else {
    console.log('Validation succeeded!');
  }
}

run();
OutputSuccess
Important Notes

Always import decorators from 'class-validator' package.

Use async validate() function to check all rules at once.

Validation errors give clear messages to help fix data.

Summary

Class-validator decorators check data rules easily.

Use them on class properties with @ syntax.

Run validate() to find errors before using data.