Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Validating Data with Pipes | Working with Data
Building Backend Applications with Nest.js

bookValidating Data with Pipes

Свайпніть щоб показати меню

DTOs define the structure of your data, but they do not validate it by default.

To ensure that incoming data is correct, you can use validation with pipes.

First, install the required packages:

npm install class-validator class-transformer

Update your DTO with validation rules:

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

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

  @IsInt()
  age: number;
}

Here is what is happening:

  • @IsString(): ensures the value is a string;
  • @IsInt(): ensures the value is a number;
  • The DTO now includes validation rules.

Next, enable validation in your application.

Open main.ts and update it:

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

app.useGlobalPipes(new ValidationPipe());

Now when a request is sent, Nest.js automatically checks the data.

If the data is invalid, the request is rejected and an error is returned.

This ensures your application only works with valid and predictable data.

question mark

What is used to validate incoming data in Nest.js?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 5. Розділ 4

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 5. Розділ 4
some-alt