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โ
| Decorator | Validation |
|---|---|
@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);
}
Related Pagesโ
- DTO Design Patterns โ DTOs
- Request Lifecycle โ request flow
- Error Handling โ errors