DEV Community

mark vachi
mark vachi

Posted on

3

Efficient Data Validation in Nestjs using class-validator: A Quick Guide

Nestjs is a Node.js framework for building efficient server-side apps. It uses TypeScript and integrates class-validator for data validation. To validate DTOs, which define data shapes, you add decorators like @IsEmail() or @IsNotEmpty() to class properties. For instance, a CreateUserDto class might look like:

import { IsEmail, IsNotEmpty, IsString } from 'class-validator';

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

  @IsNotEmpty()
  @IsString()
  password: string;

  @IsNotEmpty()
  @IsString()
  name: string;
}
Enter fullscreen mode Exit fullscreen mode

To globally apply validation, use the ValidationPipe in your main.ts:

import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}
bootstrap();
Enter fullscreen mode Exit fullscreen mode

For testing, use class-validator's functions like plainToClass and validateSync. A Jest unit test example:

import { plainToClass } from 'class-transformer';
import { validateSync } from 'class-validator';
import { CreateUserDto } from './create-user.dto';

describe('CreateUserDto', () => {
  it('should be valid with valid properties', () => {
    const createUserDto = plainToClass(CreateUserDto, {
      email: 'admin@gmail.com',
      password: 'xxxxxxxx',
      name: 'Admin',
    });
    const errors = validateSync(createUserDto);
    expect(errors).toHaveLength(0);
  });

  it('should be invalid with invalid properties', () => {
    const createUserDto = plainToClass(CreateUserDto, {
      email: 'admin@gmail.com',
      password: 'xxxxxxxx',
      name: null,
    });
    const errors = validateSync(createUserDto);
    expect(errors).toHaveLength(1);
    // Check error details...
  });
});
Enter fullscreen mode Exit fullscreen mode

Nestjs and class-validator simplify building and testing apps by using decorators to validate data. For more info, see the official Nestjs and class-validator documentation.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay