嵌套对象与数组 DTO 验证
使用 @ValidateNested、@Type 和白名单剥离功能验证嵌套对象与集合。
嵌套对象与数组 DTO 验证 是 CoddyKit 上的免费 NestJS Enterprise Backend APIs 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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.
用 AI 导师学习 TypeScript — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 20
- 课程
- 76
常见问题解答
「嵌套对象与数组 DTO 验证」课时是免费的吗?
是的 — 「嵌套对象与数组 DTO 验证」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NestJS Enterprise Backend APIs 课程的其余内容,请升级到 CoddyKit PRO。 NestJS Enterprise Backend APIs 课程共包含 4 节课。
「嵌套对象与数组 DTO 验证」这节课中我会学到什么?
使用 @ValidateNested、@Type 和白名单剥离功能验证嵌套对象与集合。 你通过在浏览器中直接运行的动手代码来练习 NestJS Enterprise Backend APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 NestJS Enterprise Backend APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 NestJS Enterprise Backend APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「嵌套对象与数组 DTO 验证」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 NestJS Enterprise Backend APIs 课中编写并运行代码吗?
能。每节 NestJS Enterprise Backend APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 嵌套对象与数组 DTO 验证
- 自定义验证器与异步约束
- 使用 ClassSerializerInterceptor 定制响应
- 条件验证与动态分组