التحقق من DTOs المتداخلة والمصفوفات
تحقق من الكائنات والمجموعات المتداخلة باستخدام @ValidateNested و@Type وإزالة الحقول غير المدرجة في القائمة المسموح بها
التحقق من DTOs المتداخلة والمصفوفات درس مجاني في NestJS Enterprise Backend APIs على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في NestJS Enterprise Backend APIs، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة NestJS Enterprise Backend APIs 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Why Nested Validation Needs Help
NestJS pairs class-validator with class-transformer through the global ValidationPipe. For flat DTOs this works out of the box: decorators on each property run automatically.
But the moment a DTO contains another object or an array of objects, validation silently stops at the boundary. The validator sees a child property, but it does not know it is a class instance whose own decorators should run.
- A nested
addressobject is treated as an opaque value. - An
itemsarray is checked for being an array, but its elements are never validated.
This lesson shows how @ValidateNested, @Type, and whitelist stripping close those gaps.
The Problem in Code
Consider an order payload with a nested address. Adding @ValidateNested alone is not enough — the validator still needs the child to be an actual AddressDto instance, not a plain object.
Without @Type, class-transformer leaves address as a plain object, so the @IsString() on city never runs. Invalid data passes through unnoticed.
import { IsString, ValidateNested } from 'class-validator';
// AddressDto's own rules will NOT run yet
class AddressDto {
@IsString()
city: string;
}
export class CreateOrderDto {
@ValidateNested() // declares intent, but lacks a target type
address: AddressDto;
}@Type Makes the Child a Real Instance
The missing piece is @Type(() => AddressDto) from class-transformer. It tells the transformer how to construct the nested value, turning the raw JSON object into a true AddressDto instance.
Only then do the child's decorators (@IsString, @IsNotEmpty, etc.) actually execute. The rule of thumb:
- @ValidateNested() → "recurse into this property".
- @Type(() => Child) → "build it as this class first".
You almost always need both together.
import { IsString, IsPostalCode, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
class AddressDto {
@IsString()
city: string;
@IsPostalCode('US')
zip: string;
}
export class CreateOrderDto {
@ValidateNested()
@Type(() => AddressDto)
address: AddressDto;
}Enabling transform in the Pipe
For @Type to take effect, the ValidationPipe must run class-transformer. Enable it globally with transform: true.
This also converts primitives: a route param string '42' becomes a number when the DTO/param type says so. Without transform, nested classes stay plain and your @Type hints are ignored.
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({
transform: true, // run class-transformer (required for @Type)
whitelist: true,
forbidNonWhitelisted: true,
}),
);
await app.listen(3000);
}
bootstrap();Validating Arrays of DTOs
Arrays of objects need the same pair, with one addition: each: true. This makes @ValidateNested({ each: true }) apply the nested validation to every element of the array.
@Type(() => ItemDto) maps each raw element into an ItemDto instance. Add @IsArray() and optionally @ArrayMinSize(1) to guard the collection shape itself.
import { IsArray, ArrayMinSize, IsString, IsInt, Min, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
class OrderItemDto {
@IsString()
sku: string;
@IsInt()
@Min(1)
quantity: number;
}
export class CreateOrderDto {
@IsArray()
@ArrayMinSize(1)
@ValidateNested({ each: true }) // validate every element
@Type(() => OrderItemDto)
items: OrderItemDto[];
}Deeply Nested Structures
The pattern composes to any depth. An order has items, and each item has its own nested discount. Each level that crosses into another class repeats the @ValidateNested + @Type pair.
Validation recurses top-down: the order validates its items array, each item validates its discount object, and every leaf decorator runs. There is no special "deep" flag — you just apply the same two decorators at each boundary.
import { ValidateNested, IsString, IsNumber, Max, Min } from 'class-validator';
import { Type } from 'class-transformer';
class DiscountDto {
@IsNumber()
@Min(0)
@Max(1)
rate: number;
}
class OrderItemDto {
@IsString()
sku: string;
@ValidateNested()
@Type(() => DiscountDto)
discount: DiscountDto;
}
export class CreateOrderDto {
@ValidateNested({ each: true })
@Type(() => OrderItemDto)
items: OrderItemDto[];
}whitelist Strips Unknown Properties
whitelist: true removes any property in the incoming payload that has no validation decorator on the DTO. This is a core security defense: clients cannot smuggle extra fields like isAdmin or role into your entities.
Crucially, whitelisting works recursively on validated nested objects. If a nested AddressDto only declares city and zip, an injected country field on the nested object is stripped too — but only because @ValidateNested + @Type made the validator descend into it.
forbidNonWhitelisted: Reject vs Strip
There are two postures for unknown fields:
- whitelist: true — silently strips unknown properties and continues.
- whitelist + forbidNonWhitelisted: true — rejects the whole request with
400, listing the offending property.
For public APIs, forbidding is stricter and surfaces client mistakes early. Note that forbidNonWhitelisted only has an effect when whitelist is also enabled.
// Payload: { "city": "Austin", "zip": "73301", "hack": "x" }
// whitelist: true (only)
// -> { city: 'Austin', zip: '73301' } // 'hack' stripped
// whitelist: true + forbidNonWhitelisted: true
// -> 400 Bad Request
// -> message: ["property hack should not exist"]A Pure class-validator Example You Can Run
Outside NestJS, the same engine works directly. This standalone snippet builds a nested instance with plainToInstance and validates it with validateSync — exactly what the ValidationPipe does internally.
Run it to see how @ValidateNested + @Type surface a nested error.
import 'reflect-metadata';
import { IsString, IsInt, Min, ValidateNested, validateSync } from 'class-validator';
import { plainToInstance, Type } from 'class-transformer';
class ItemDto {
@IsString() sku!: string;
@IsInt() @Min(1) quantity!: number;
}
class OrderDto {
@ValidateNested({ each: true })
@Type(() => ItemDto)
items!: ItemDto[];
}
const payload = { items: [{ sku: 'A1', quantity: 0 }] };
const dto = plainToInstance(OrderDto, payload);
const errors = validateSync(dto);
console.log(JSON.stringify(errors[0].children[0].children, null, 2));Optional and Nullable Nested Objects
A nested object that may be absent should be marked @IsOptional(). When present, it is still validated; when missing, it is skipped. Combine this with @ValidateNested and @Type as usual.
For arrays, @IsOptional() lets the whole array be omitted, while @ArrayMinSize still enforces a minimum once the array is provided. Keep each: true so present elements remain validated.
import { IsOptional, ValidateNested, IsString } from 'class-validator';
import { Type } from 'class-transformer';
class BillingDto {
@IsString()
taxId: string;
}
export class UpdateAccountDto {
@IsOptional()
@ValidateNested()
@Type(() => BillingDto)
billing?: BillingDto;
}Common Pitfalls
Watch for these failures, which all let bad data through silently:
- Forgetting @Type — nested object stays plain; child decorators never run.
- Forgetting transform: true — the pipe never invokes class-transformer, so
@Typeis ignored. - Missing each: true on arrays — only the first/whole array is checked, not each element.
- No reflect-metadata import — decorators emit no metadata; validation no-ops.
- Disabling whitelist — unknown fields flow straight into your service layer.
Quick Check
You have an array of nested DTOs to validate. Which combination is required?
Recap
You now know how to validate nested and array DTOs in NestJS:
- @ValidateNested() tells the validator to recurse into a child object; add { each: true } for arrays.
- @Type(() => Child) from class-transformer turns raw JSON into real class instances so child decorators run.
- transform: true on the ValidationPipe is mandatory for @Type to take effect.
- whitelist: true strips undeclared properties recursively; forbidNonWhitelisted: true rejects them with a 400 instead.
- Always import reflect-metadata and repeat the @ValidateNested + @Type pair at every class boundary, however deep.
الأسئلة الشائعة
هل درس «التحقق من DTOs المتداخلة والمصفوفات» مجاني؟
نعم — نص درس «التحقق من DTOs المتداخلة والمصفوفات» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة NestJS Enterprise Backend APIs، انتقل إلى CoddyKit PRO. تتضمن دورة NestJS Enterprise Backend APIs 4 دروس في المجموع.
ماذا ستتعلم في «التحقق من DTOs المتداخلة والمصفوفات»؟
تحقق من الكائنات والمجموعات المتداخلة باستخدام @ValidateNested و@Type وإزالة الحقول غير المدرجة في القائمة المسموح بها تتمرن على NestJS Enterprise Backend APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ NestJS Enterprise Backend APIs؟
لا تُشترط خبرة سابقة. NestJS Enterprise Backend APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «التحقق من DTOs المتداخلة والمصفوفات»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس NestJS Enterprise Backend APIs هذا؟
نعم. كل درس في NestJS Enterprise Backend APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- التحقق من DTOs المتداخلة والمصفوفات
- Validators مخصصة وقيود غير متزامنة
- تشكيل الاستجابات باستخدام ClassSerializerInterceptor
- التحقق الشرطي والمجموعات الديناميكية