How to Validate Nested Objects with Class-Validator in Nest.js?
Last Updated :
16 Oct, 2024
Validating nested objects in Nest.js using the class validator is crucial for ensuring the integrity and structure of incoming data, especially when dealing with complex data models. Class validator works seamlessly with Nest.js to validate incoming request data using Data Transfer Objects (DTOs). This process helps in enforcing rules, such as required fields, data types, and nested object validation.
These are the following topics that we are going to explore:
Key Concepts
- DTOs (Data Transfer Objects): Used to define the shape and structure of data being transferred, DTOs in Nest.js help in validating and transforming the data.
- Nested Objects: When DTOs contain properties that are objects themselves, those nested objects need their own validation rules.
- class-validator: A library that provides a set of decorators and utility functions to validate objects against specified rules.
- class-transformer: This library helps in transforming plain JavaScript objects into instances of classes, which is essential for nested validation.
How Does It Work?
- Define DTOs: Create classes that represent the structure of the data, using class-validator decorators to specify validation rules.
- Nested Validation: For nested objects within a DTO, use the @ValidateNested decorator to ensure that nested objects are validated according to their own rules.
- Apply in Controllers: Use these DTOs in controller methods to automatically validate incoming requests.
- Global Validation Pipe: Enable a global validation pipe in Nest.js to enforce validation across the entire application.
Why Validate Nested Objects?
- Data Integrity: Ensures that the nested objects conform to the expected structure and rules.
- Error Handling: Provides clear error messages if the data is invalid, helping with debugging and client-side validation feedback.
- Security: Prevents malformed or malicious data from reaching your business logic and database.
Steps to Validate nested objects with class-validator
Here's a complete setup to validate nested objects with class-validator in a Nest.js application. This example includes defining the DTOs, setting up the controller, and enabling validation globally.
Step 1: Create a project using the below command:
npm install -g @Nest.js/cli
nest new my-nest-app
Project Structure:
Project Structure Step 2: Install Dependencies
First, install class-validator and class-transformer if you haven't already
cd my-nest-app
npm install class-validator class-transformer
Updated Dependencies:
"dependencies": {
"@Nest.js/common": "^10.0.0",
"@Nest.js/config": "^3.2.3",
"@Nest.js/core": "^10.0.0",
"@Nest.js/platform-express": "^10.0.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
}
Step 3: Create DTOs
- Create a DTO for the nested object, e.g., AddressDto.
JavaScript
// src/users/address.dto.ts
import { IsString, IsNotEmpty } from 'class-validator';
export class AddressDto {
@IsString()
@IsNotEmpty()
street: string;
@IsString()
@IsNotEmpty()
city: string;
@IsString()
@IsNotEmpty()
country: string;
}
Step 4: CreateUserDto - Main Object with Nested DTO
Create the main DTO, e.g., CreateUserDto, which includes the nested AddressDto:
JavaScript
// src/users/create-user.dto.ts
import { IsString, IsNotEmpty, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
import { AddressDto } from './address.dto';
export class CreateUserDto {
@IsString()
@IsNotEmpty()
name: string;
@IsString()
@IsNotEmpty()
email: string;
// Validate the nested object
@ValidateNested()
// Transform to AddressDto class instance
@Type(() => AddressDto)
address: AddressDto;
}
Step 5: Create the Controller
Set up a controller that uses the CreateUserDto to validate incoming requests:
JavaScript
// src/users/users.controller.ts
import { Body, Controller, Post } from '@nestjs/common';
import { CreateUserDto } from './create-user.dto';
@Controller('users')
export class UsersController {
@Post()
async createUser(@Body() createUserDto: CreateUserDto) {
// Logic to handle user creation (e.g., save to database)
return createUserDto;
}
}
Step 6: Create the Module
Create a module to register the controller:
JavaScript
// src/users/users.module.ts
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
@Module({
controllers: [UsersController],
})
export class UsersModule {}
Step 7: Include the Module in the Application
Include the UsersModule in your main application module:
JavaScript
// src/app.module.ts
import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';
@Module({
imports: [UsersModule],
})
export class AppModule {}
Step 8: Enable Global Validation Pipe
Enable global validation in the main.ts file to ensure that all incoming requests are validated according to the DTOs:
JavaScript
// src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe()); // Enable global validation
await app.listen(3000);
}
bootstrap();
Test the Endpoint
Example Request Payload:
- Open Postman or Insomnia.
- Set the request type to POST.
- Enter the URL: http://localhost:3000/users.
- In the "Body" tab, choose "raw" and set the format to "JSON".
- Enter the JSON payload:
{
"name": "John Doe",
"email": "[email protected]",
"address": {
"street": "123 Main St",
"city": "Anytown",
"country": "USA"
}
}
Click "Send" to make the request.
Output:
With ValidationExample Invalid Request Payload:
{
"name": "John Doe",
"email": "[email protected]",
"address": {
"street": "",
"city": "Anytown"
}
}
Output:
Invalid Request
Similar Reads
What is Json Schema and How to Validate it with Postman Scripting? JSON stands for JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is often used to transmit data between a server and a web application. It supports data structures like arrays and objects an
4 min read
How to Define Strongly Type Nested Object Keys with Generics in TypeScript ? We will look into the effective use of generics in TypeScript to ensure type safety when working with nested objects. By employing generics, developers can establish strongly typed keys for nested objects, significantly reducing the likelihood of runtime errors and enhancing code maintainability. Ta
2 min read
How to apply validation on Props in ReactJS ? Need of Validating Props in React JS Props are used to pass the read-only attributes to React components. For the proper functioning of components and to avoid future bugs and glitches it is necessary that props are passed correctly. Hence, it is required to use props validation to improve the react
3 min read
How to Add Form Validation In Next.js ? Forms play a crucial role in modern web applications by ensuring the accuracy and validity of data. NeÂxt.js, a versatile framework for building ReÂact applications, offers form validation that helps verify useÂr input against predefined criteÂria, provides immediate feedback, and enhances data qual
3 min read
How to Create and Validate JSON Schema in MongoDB? JSON Schema validation in MongoDB allows you to enforce the structure of documents in a collection. This ensures data integrity by validating documents against defined schemas before they are inserted or updated. In this article, we will cover how to create and validate JSON Schema in MongoDB using
5 min read
How to Validate XML in JavaScript ? Validation of XML is important for ensuring data integrity and adherence to XML standards in JavaScript. There are various approaches available in JavaScript using which validation of the XML can be done which are described as follows: Table of Content Using DOM ParserUsing Tag MatchingUsing DOM Par
2 min read
How to check if a value is object-like in JavaScript ? In JavaScript, objects are a collection of related data. It is also a container for name-value pairs. In JavaScript, we can check the type of value in many ways. Basically, we check if a value is object-like using typeof, instanceof, constructor, and Object.prototype.toString.call(k). All of the ope
4 min read
How To Write Integration Tests in NestJS? Integration testing is an important part of software development, ensuring that various parts of your application work together as expected. In NestJS, integration testing allows you to test the interaction between different modules, services, and controllers. In this article, we will guide you thro
8 min read
How to Properly Watch for Nested Data in VueJS ? In Vue.js, we can watch the nested data to properly control the changes within the nested properties. In this article, we will explore both of the approaches with the practical implementation of these approaches in terms of examples and outputs. We can watch this by using two different approaches: T
3 min read
How to trigger Form Validators in Angular2 ? In Angular 2, the best way to deal with complex forms is by using Reactive forms. Below we are going to elaborate on how to trigger form validators for login page. In reactive forms, we use FormControl and by using this, we get access to sub-fields of form and their properties. Some of their propert
4 min read