跳到主要内容

Pipe Validation Deep Dive

Input validation and transformation using NestJS pipes.

Global Validation Pipe

// main.ts
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // Strip unknown properties
forbidNonWhitelisted: true, // Throw on unknown properties
transform: true, // Auto-transform payloads to DTO instances
transformOptions: {
enableImplicitConversion: true,
},
}),
);

Validation Flow

Common Decorators

DecoratorValidation
@IsString()Must be string
@IsNotEmpty()Cannot be empty
@IsEmail()Valid email
@IsUUID('4')Valid UUID v4
@IsEnum(MyEnum)Must be enum member
@IsDateString()ISO 8601 date string
@IsOptional()Skip if undefined
@ValidateNested()Validate nested object
@Type(() => Class)Transform to class
@Transform(fn)Custom transformation

Custom Pipe

@Injectable()
export class TenantOrganizationPipe implements PipeTransform {
transform(value: any) {
const tenantId = RequestContext.currentTenantId();
return { ...value, tenantId };
}
}

UUID Parameter Pipe

@Get(':id')
async findOne(@Param('id', new ParseUUIDPipe()) id: string) {
return this.service.findOneByIdString(id);
}