Skip to content
NestPath

Exercises — Validation with Pipes

Covers: why TS types are compile-time lies, class-validator vs class-transformer roles, ValidationPipe internals, whitelist / forbidNonWhitelisted / transform, decorator catalogue, @IsOptional() mechanics, custom messages, PartialType.


Part A — Concept Checks (closed book)

  1. Explain "compile-time lie" in your own words. Why doesn't title: string reject title: 123 at runtime?
  2. What does class-transformer do, what does class-validator do, and why is each useless without the other?
  3. Describe the 3 internal steps ValidationPipe performs on an incoming body, in order.
  4. Define precisely: whitelist: true, forbidNonWhitelisted: true, transform: true. Which one makes ParseIntPipe technically droppable?
  5. What does @IsOptional() change about the other validators on the same property? Why does its position matter?
  6. @IsString() vs @IsNotEmpty() — what does each catch that the other doesn't? Give a value rejected by one but accepted by the other (both directions).
  7. What exactly does PartialType(CreateTaskDto) do to (a) the properties, (b) their existing decorators, (c) their optionality?
  8. Where in the lifecycle do pipes run relative to guards and interceptors? Why does that placement matter for validation?
  9. When validation fails on 3 properties at once, what does the client receive — 3 responses or 1? Describe the shape.
  10. Why is forbidNonWhitelisted suggested for development but sometimes relaxed to plain whitelist in production?

Part B — Guided Exercises

B1. Wire it up

  1. Install class-validator and class-transformer.
  2. Register a global ValidationPipe in main.ts with all three options from the lesson.
  3. Decorate CreateTaskDto: title → string, not empty, max 100; description → string, not empty, max 500. Add one custom message to any decorator.
  4. Rewrite UpdateTaskDto using PartialType (@nestjs/mapped-types) + an @IsOptional() @IsBoolean() done field.

Checkpoint — run all of these and record the exact responses: - POST /tasks { "title": "", "description": 42, "hackField": "x" } → 400 listing all errors incl. "property hackField should not exist" - POST /tasks { "title": "ok", "description": "ok" } → 201 - PATCH /tasks/1 { "done": true } → 200, only done changed - PATCH /tasks/1 { "done": "true" } → 400 (string is not boolean)

B2. Validate the Notes resource

Apply everything to NotesModule from Module 01: - text: string, not empty, max 280 (tweet-sized), custom message on max length. - pinned: optional boolean on update only — creating a note never accepts pinned. Verify a create with pinned: true is rejected by forbidNonWhitelisted.

B3. Enum + number validation

Formalize the priority field from Module 01's C3: 1. Create export enum TaskPriority { LOW = 'low', MEDIUM = 'medium', HIGH = 'high' }. 2. @IsEnum(TaskPriority) + @IsOptional() on create (defaults to medium in the service). 3. Add estimatedHours?: number with @IsInt(), @Min(1), @Max(100). 4. Test: "estimatedHours": "5" (string) — does it pass? Explain the result in terms of transform: true and then add @Type(() => Number) and observe the difference. Write down what you learned about implicit vs explicit conversion.

B4. Nested object validation

Add an optional meta object to CreateTaskDto:

json
{ "title": "...", "description": "...", "meta": { "source": "web", "tags": ["a","b"] } }

Requirements: meta.source must be a string; meta.tags an array of strings with at least 1 element. You'll need @ValidateNested(), @Type(() => TaskMetaDto), @IsArray(), @ArrayMinSize(1), @IsString({ each: true }). Prove it works by sending { "meta": { "source": 5 } } and getting a nested error message.


Part C — Independent Challenges

C1. Registration DTO (preview of Module 07)

Build RegisterDto with: - email: valid email - username: string, 3–20 chars, alphanumeric only (regex) - password: min 8 chars, must contain at least one number and one letter (regex), with a human-friendly custom message

C2. Query DTO validation

Convert Module 01's C1 query filtering to a validated QueryTasksDto (done?: boolean, search?: string, page?: number, limit?: number with sane min/max). Use @Query() with the DTO type. Gotcha to solve: query params arrive as strings — make done=true become a real boolean (research @Transform from class-transformer).

C3. Per-route pipe override

Keep the global pipe, but make one specific route (POST /notes/import) accept unknown extra properties (whitelist off just there). Figure out how @UsePipes(new ValidationPipe({...})) at route level interacts with the global one.


Part D — Debug Drills

D1

ts
export class UpdateTaskDto {
  @IsString()
  @IsOptional()
  title?: string;
}

PATCH /tasks/1 with {} fails intermittently in a teammate's branch but works in the lesson's version. What ordering claim does the lesson make, is this snippet actually broken, and what's the safe convention? (Research what class-validator really does with decorator order, then answer honestly.)

D2

ts
export interface CreateTaskDto {
  title: string;
  description: string;
}

Everything compiles; validation silently never runs. Why?

D3

main.ts has the global pipe, but POST /tasks with garbage still reaches the service in your e2e test that builds the app via Test.createTestingModule + createNestApplication(). What common mistake causes validation to vanish in tests?

D4

ts
@IsNotEmpty()
@IsString()
@MaxLength(100)
title: string;

Client sends "title": 123. The 400 lists two failed constraints for title in some setups, one in others. Which decorators can fire for a number, and why doesn't @IsNotEmpty() save you here?

D5

ts
export class UpdateTaskDto extends PartialType(CreateTaskDto) {
  done?: boolean;
}

{ "done": "yes" } sails through and corrupts data. Why did PartialType not protect done, and what two decorators are missing?


Part E — Prediction Drills

Global pipe = { whitelist: true, forbidNonWhitelisted: true, transform: true }. Predict status + key error messages:

  1. POST /tasks { "title": "a".repeat(101), "description": "ok" }
  2. POST /tasks { "title": "ok" } (no description)
  3. PATCH /tasks/1 { "title": null }
  4. POST /tasks { "title": "ok", "description": "ok", "done": true } — remember which DTO has done.
  5. Same request as 4, but options changed to { whitelist: true, forbidNonWhitelisted: false }.

Part F — Stretch Goals

  1. Write a custom validator @IsNotProfane() using registerDecorator that rejects titles containing words from a blocklist.
  2. Explore ValidationPipe's exceptionFactory option: reshape the 400 error into { field, constraint, message }[] — you'll appreciate this in Module 03.
  3. Add stopAtFirstError: true and document the UX trade-off vs collecting all errors.

Self-Assessment Checklist

  • I can explain transformer vs validator roles without notes
  • I know exactly what each of the 3 pipe options does and have observed each
  • I can validate nested objects and arrays
  • I can build an Update DTO with PartialType and extend it safely
  • I understand why query params need @Type/@Transform help
  • Controller/service code stayed untouched throughout this module

Answers & Hints

A1: TS types are erased during compilation; at runtime req.body is whatever JSON arrived. Annotations constrain your code, not the network.

A2: transformer: plain object → class instance (plainToInstance); validator: reads decorator metadata off the instance and checks rules. Decorators live on class instances, so without transformation there's nothing to validate; without validation the instance is just a cast.

A3: ① plainToInstance(Dto, body) ② validate(instance) against decorator metadata ③ pass instance to controller or throw BadRequestException with all messages.

A4: whitelist strips undecorated props; forbidNonWhitelisted 400s on them instead; transform returns real class instances + coerces primitives (param strings → numbers) — that coercion is what makes ParseIntPipe droppable.

A5: If the value is undefined/null, all other validators on that property are skipped. Convention: put it first for readability (validation itself isn't order-dependent for this decorator, but the convention prevents confusion).

A6: @IsString() accepts "" (it is a string) but rejects 123; @IsNotEmpty() rejects ""/null/undefined but accepts 123 (non-empty). You need both.

A7: (a) copies all properties, (b) inherits their validation decorators, (c) wraps each with @IsOptional() — everything becomes optional but still validated when present.

A8: Middleware → Guards → Interceptors(pre) → Pipes → Controller. Auth is decided before you spend cycles validating; controller can trust its input completely.

A9: One 400 response; message is an array with one entry per failed constraint — all errors at once.

A10: In dev, loud failures train API consumers. In prod, silently stripping unknown fields is more forgiving to older clients while still protecting you.

D1: Not actually broken — @IsOptional() works regardless of stacking order; the lesson's "order matters" is about readable convention. If the teammate's branch fails, look elsewhere (e.g., missing global pipe). Honest answer: verify claims empirically.

D2: It's an interface — erased at runtime, cannot hold decorators, transformer/validator have nothing to work with. Must be a class.

D3: The test app never called app.useGlobalPipes(...) — global pipes from main.ts don't apply because main.ts never runs in tests. Re-register in the test setup (or use APP_PIPE provider so it lives in the DI container and applies everywhere).

D4: For 123: @IsString() fails, @MaxLength fails (not a string). @IsNotEmpty() passes — 123 isn't empty. Emptiness ≠ type correctness.

D5: PartialType only processes CreateTaskDto's fields; done is a new field you declared bare. Missing @IsOptional() + @IsBoolean() — and with whitelist on, an undecorated done would actually be stripped or forbidden, which is its own surprise.

E1: 400, "title must be shorter than or equal to 100 characters". E2: 400, both "description must be a string"-family and "description should not be empty" style messages (constraints on a missing required field). E3: 400 — @IsOptional() skips on undefined/null? Careful: class-validator's @IsOptional skips both undefined and null, so this passes validation and Object.assign sets title: null. (If you used @IsDefined semantics or want to reject null, you need extra handling — good discussion point.) E4: 400 — done isn't on CreateTaskDto; forbidNonWhitelisted → "property done should not exist". E5: 201 — done silently stripped; task created with done: false from the service default.