ValidationPipe and class-validator decorators.
Overview
Validation is enabled by default when you haveclass-validator and class-transformer installed. The framework uses:
- DTOs: Custom DTO classes you provide
- Entity classes: With validation groups when no DTO is specified
- ValidationPipe: NestJS validation pipe with customizable options
Basic validation setup
Using DTOs
Create DTO classes with validation decorators:CreateUserDto.ts
Using entity validation groups
If you don’t provide DTOs, you can use validation groups directly on your entity:User.entity.ts
Validation groups
NestJS CRUD defines two validation groups:How groups work
- CREATE group: Applied to POST (create) operations
- UPDATE group: Applied to PATCH (update) operations
- always: true: Validation applies to all operations
Configuring ValidationPipe
Customize validation behavior using thevalidation option:
Common ValidationPipe options
boolean
default:false
Strip properties that don’t have any decorators.
boolean
default:false
Throw an error if non-whitelisted properties are present.
boolean
default:false
Automatically transform payloads to DTO instances.
ClassTransformOptions
Options for class-transformer.
boolean
default:false
Skip validation of properties that are not in the payload.
boolean
default:true
Throw an error if unknown objects are validated.
number
default:400
HTTP status code to use on validation errors.
Recommended configuration
Disabling validation
Setvalidation: false to disable automatic validation:
Nested object validation
Validate nested objects using@ValidateNested() and @Type():
Bulk create validation
Bulk create operations use a special DTO that validates an array:The framework automatically creates this bulk DTO when validation is enabled. You don’t need to create it manually.
Validation error responses
When validation fails, NestJS returns a 400 Bad Request with error details:Custom validation decorators
Create custom validators for business logic:Conditional validation
Use@ValidateIf() for conditional validation:
Async validation
Create async validators for database checks:Remember to register async validator constraints as providers in your module.
Update vs Replace validation
- PATCH (update): Partial updates, fields are optional
- PUT (replace): Full replacement, typically requires all fields
Best practices
Always validate user input
Always validate user input
Never trust client data. Always use validation on create and update operations:
Use DTOs for complex validation
Use DTOs for complex validation
For complex validation requirements, create dedicated DTO classes instead of relying on entity validation groups:
Separate DTOs from entities
Separate DTOs from entities
Keep validation DTOs separate from database entities for better separation of concerns and flexibility.
Document validation rules
Document validation rules
Use custom error messages to clearly communicate validation requirements: