0Pricing
NestJS Enterprise Backend APIs · Lesson

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

  1. Nested and Array DTO Validation
  2. Custom Validators and Async Constraints
  3. Response Shaping with ClassSerializerInterceptor
  4. Conditional Validation and Dynamic Groups
← Back to NestJS Enterprise Backend APIs