0Pricing
NestJS Enterprise Backend APIs · درس

التحقق الشرطي والمجموعات الديناميكية

تطبيق قواعد تعتمد على السياق باستخدام @ValidateIf ومجموعات التحقق لكل نقطة نهاية.

التحقق الشرطي والمجموعات الديناميكية درس مجاني في NestJS Enterprise Backend APIs على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في NestJS Enterprise Backend APIs، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة NestJS Enterprise Backend APIs 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

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;
}

@ValidateIf vs @IsOptional

These two look similar but differ in intent:

  • @IsOptional — skips validation when the value is null or undefined, unconditionally.
  • @ValidateIf — skips (or enables) validation based on any condition you write, including other fields.

Crucially, @ValidateIf returning false also suppresses errors even when a value is present. Use it when the presence requirement itself depends on context.

Forbidding a Field Conditionally

You can flip the logic: require a field to be absent under a condition. Combine @ValidateIf with @IsEmpty so the field is rejected when it should not appear.

Here, a discountCode is only allowed for promo orders; supplying it on a standard order fails validation.

import { ValidateIf, IsEmpty, IsString, IsIn } from 'class-validator';

export class OrderDto {
  @IsIn(['standard', 'promo'])
  type: 'standard' | 'promo';

  // Must be EMPTY unless this is a promo order
  @ValidateIf((o: OrderDto) => o.type !== 'promo')
  @IsEmpty({ message: 'discountCode is only allowed on promo orders' })
  discountCode?: string;
}

Introducing Validation Groups

A validation group is just a string label attached to a decorator via its options. Constraints with no group always run; constraints assigned to a group run only when that group is requested at validation time.

This lets one DTO express different rule sets — e.g. stricter rules at create than at update — without duplicating the class.

import { IsString, MinLength, IsNotEmpty } from 'class-validator';

export const CREATE = 'create';
export const UPDATE = 'update';

export class ProfileDto {
  @IsNotEmpty({ groups: [CREATE] })
  @IsString({ groups: [CREATE, UPDATE] })
  @MinLength(2, { groups: [CREATE, UPDATE] })
  displayName?: string;
}

Activating a Group

Groups do nothing until you pass them to the validator. With the imperative API you supply { groups: [...] } to validate(). In NestJS you forward the same option through the ValidationPipe.

Important default: when you request a group, constraints that belong to no group are still applied unless you set strictGroups or always options.

import { validate } from 'class-validator';
import { ProfileDto, UPDATE } from './profile.dto';

async function run() {
  const dto = Object.assign(new ProfileDto(), { displayName: '' });

  // Only UPDATE-group constraints (plus groupless ones) run.
  const errors = await validate(dto, { groups: [UPDATE] });
  console.log('error count:', errors.length);
}
run();

Wiring Groups into a NestJS Pipe

NestJS exposes validation-group options on ValidationPipe. The cleanest pattern is a per-route pipe whose groups declare which rule set this endpoint enforces.

Set always: true if you want groupless constraints to keep running regardless of the active group, and strictGroups: true to reject constraints whose group was not requested.

import { Controller, Post, Body, ValidationPipe } from '@nestjs/common';
import { ProfileDto, CREATE } from './profile.dto';

@Controller('profiles')
export class ProfileController {
  @Post()
  create(
    @Body(new ValidationPipe({ groups: [CREATE], always: true }))
    dto: ProfileDto,
  ) {
    return { ok: true, dto };
  }
}

One DTO, Two Endpoints

The payoff: a single DTO drives both POST (create) and PATCH (update) with different strictness. Each route binds its own ValidationPipe with the matching group.

Avoid the temptation to keep separate CreateDto and UpdateDto when only required-ness differs — groups remove that duplication and keep field types in one place.

import { Controller, Post, Patch, Body, ValidationPipe } from '@nestjs/common';
import { ProfileDto, CREATE, UPDATE } from './profile.dto';

@Controller('profiles')
export class ProfileController {
  @Post()
  create(@Body(new ValidationPipe({ groups: [CREATE] })) dto: ProfileDto) {
    return dto;
  }

  @Patch(':id')
  update(@Body(new ValidationPipe({ groups: [UPDATE] })) dto: ProfileDto) {
    return dto;
  }
}

Dynamic Groups from Request Context

Sometimes the group depends on runtime data — the caller's role, a feature flag, a tenant tier. Since the ValidationPipe instance is built at route-declaration time, derive the group inside a small custom pipe that reads the request, then call validate yourself with the computed groups.

import { Injectable, PipeTransform, BadRequestException } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { REQUEST } from '@nestjs/core';
import { Inject, Scope } from '@nestjs/common';

@Injectable({ scope: Scope.REQUEST })
export class RoleAwareValidationPipe implements PipeTransform {
  constructor(@Inject(REQUEST) private readonly req: any) {}

  async transform(value: any, meta: any) {
    const groups = this.req.user?.role === 'admin' ? ['admin'] : ['user'];
    const dto = plainToInstance(meta.metatype, value);
    const errors = await validate(dto, { groups, always: true });
    if (errors.length) throw new BadRequestException(errors);
    return dto;
  }
}

Combining @ValidateIf With Groups

The two mechanisms compose. @ValidateIf handles within-payload dependencies (field A depends on field B); groups handle which endpoint/role is calling. A constraint runs only when its group is active and its @ValidateIf condition holds.

Below, cancelReason is required — but only in the cancel group and only when the status is actually being set to cancelled.

import { ValidateIf, IsNotEmpty, IsIn } from 'class-validator';

export const CANCEL = 'cancel';

export class UpdateBookingDto {
  @IsIn(['active', 'cancelled'], { groups: [CANCEL] })
  status: 'active' | 'cancelled';

  @ValidateIf((o: UpdateBookingDto) => o.status === 'cancelled', { groups: [CANCEL] })
  @IsNotEmpty({ groups: [CANCEL] })
  cancelReason?: string;
}

Pure Logic You Can Verify

Strip away the framework and the decision is just predicate logic: a constraint fires when its group is requested and its condition is true. The function below mirrors how class-validator decides whether to enforce a single constraint, so you can reason about edge cases without a server.

type Ctx = { activeGroups: string[]; obj: Record<string, unknown> };

function shouldValidate(
  constraintGroups: string[],
  validateIf: (o: Record<string, unknown>) => boolean,
  ctx: Ctx,
): boolean {
  const groupMatches =
    constraintGroups.length === 0 ||
    constraintGroups.some((g) => ctx.activeGroups.includes(g));
  return groupMatches && validateIf(ctx.obj);
}

const ctx: Ctx = { activeGroups: ['cancel'], obj: { status: 'cancelled' } };
const fires = shouldValidate(['cancel'], (o) => o.status === 'cancelled', ctx);
console.log('cancelReason enforced?', fires); // true

const skip = shouldValidate(['create'], () => true, ctx);
console.log('create-only rule enforced?', skip); // false

Quick Check

Consider this property decorated with @ValidateIf.

Recap

You learned to make validation context-aware in NestJS:

  • @ValidateIf(cb) enables or fully skips a property's constraint chain based on a runtime predicate over the payload — ideal for inter-field dependencies.
  • Validation groups label constraints so one DTO serves multiple endpoints/roles; activate them via ValidationPipe({ groups }).
  • Tune behavior with always (groupless rules still run) and strictGroups (reject unrequested-group constraints).
  • For dynamic groups from request context (role, tenant), use a request-scoped pipe that computes groups and calls validate directly.
  • The mechanisms compose: a constraint fires only when its group is active and its @ValidateIf condition is true.

الأسئلة الشائعة

هل درس «التحقق الشرطي والمجموعات الديناميكية» مجاني؟

نعم — نص درس «التحقق الشرطي والمجموعات الديناميكية» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة NestJS Enterprise Backend APIs، انتقل إلى CoddyKit PRO. تتضمن دورة NestJS Enterprise Backend APIs 4 دروس في المجموع.

ماذا ستتعلم في «التحقق الشرطي والمجموعات الديناميكية»؟

تطبيق قواعد تعتمد على السياق باستخدام @ValidateIf ومجموعات التحقق لكل نقطة نهاية. تتمرن على NestJS Enterprise Backend APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ NestJS Enterprise Backend APIs؟

لا تُشترط خبرة سابقة. NestJS Enterprise Backend APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.

كم من الوقت يستغرق درس «التحقق الشرطي والمجموعات الديناميكية»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس NestJS Enterprise Backend APIs هذا؟

نعم. كل درس في NestJS Enterprise Backend APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. التحقق من DTOs المتداخلة والمصفوفات
  2. Validators مخصصة وقيود غير متزامنة
  3. تشكيل الاستجابات باستخدام ClassSerializerInterceptor
  4. التحقق الشرطي والمجموعات الديناميكية
← العودة إلى NestJS Enterprise Backend APIs