Conditional Validation and Dynamic Groups
Apply context-dependent rules with @ValidateIf and validation groups per endpoint.
Why Conditional Validation?
Real enterprise endpoints rarely need the same rules on every request. A field can be required in one situation and forbidden in another. Two tools in class-validator solve this:
- @ValidateIf — runs (or skips) a property's validators based on a condition computed from the object itself.
- Validation groups — named sets of constraints, activated per call so one DTO can serve multiple endpoints.
This lesson shows how to combine both to keep a single DTO authoritative across create, update, and role-specific flows.
The Core Idea Behind @ValidateIf
@ValidateIf(cb) takes a callback (object, value) => boolean. When it returns false, class-validator ignores all other decorators on that property — including @IsNotEmpty and even @IsOptional. When it returns true, validation proceeds normally.
Think of it as a runtime switch placed in front of the property's constraint chain.
import { ValidateIf, IsNotEmpty, IsString } from 'class-validator';
export class PaymentDto {
@IsString()
method: 'card' | 'invoice';
// cardToken is validated ONLY when method === 'card'
@ValidateIf((o: PaymentDto) => o.method === 'card')
@IsNotEmpty()
@IsString()
cardToken?: string;
}All lessons in this course
- Nested and Array DTO Validation
- Custom Validators and Async Constraints
- Response Shaping with ClassSerializerInterceptor
- Conditional Validation and Dynamic Groups