Bird
Raised Fist0
NestJSframework~20 mins

ValidationPipe setup in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
ValidationPipe Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when ValidationPipe rejects invalid input?
Consider a NestJS controller using ValidationPipe globally. What is the response behavior when a request body fails validation?
NestJS
import { Controller, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';
import { IsInt, Min } from 'class-validator';

class AgeDto {
  @IsInt()
  @Min(18)
  age: number;
}

@Controller('users')
export class UserController {
  @Post('age')
  @UsePipes(new ValidationPipe())
  setAge(@Body() ageDto: AgeDto) {
    return { message: `Age set to ${ageDto.age}` };
  }
}
AThe server ignores validation and processes the request normally.
BThe server responds with HTTP 400 and a detailed error message about validation failure.
CThe server crashes with an unhandled exception.
DThe server responds with HTTP 500 Internal Server Error.
Attempts:
2 left
💡 Hint
Think about what ValidationPipe does when input does not meet the rules.
📝 Syntax
intermediate
1:30remaining
Which option correctly enables whitelist in ValidationPipe?
You want ValidationPipe to strip out any properties not defined in the DTO. Which code snippet correctly sets this up?
Anew ValidationPipe({ whitelist: true })
Bnew ValidationPipe({ removeExtra: true })
Cnew ValidationPipe({ stripUnknown: true })
Dnew ValidationPipe({ filter: true })
Attempts:
2 left
💡 Hint
Check the official option name for removing extra properties.
❓ state_output
advanced
2:00remaining
What is the output when transform is enabled in ValidationPipe?
Given this DTO and controller, what is the type of the parameter inside the method when ValidationPipe has transform enabled?
NestJS
import { Controller, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';
import { IsString } from 'class-validator';

class NameDto {
  @IsString()
  name: string;
}

@Controller('hello')
export class HelloController {
  @Post('name')
  @UsePipes(new ValidationPipe({ transform: true }))
  greet(@Body() nameDto: NameDto) {
    return typeof nameDto;
  }
}
A"undefined"
B"string"
C"number"
D"object"
Attempts:
2 left
💡 Hint
Transform converts plain JSON to class instance.
🔧 Debug
advanced
2:30remaining
Why does ValidationPipe not validate nested objects by default?
Given this DTO with a nested object, why does ValidationPipe not validate the nested properties without extra setup?
NestJS
import { IsString, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';

class AddressDto {
  @IsString()
  street: string;
}

class UserDto {
  @IsString()
  name: string;

  @ValidateNested()
  @Type(() => AddressDto)
  address: AddressDto;
}
ABecause nested objects are ignored unless transform is false.
BBecause ValidationPipe only validates primitive types by default.
CBecause ValidationPipe requires the nested property to be decorated with @ValidateNested and Type() decorators.
DBecause ValidationPipe does not support nested validation at all.
Attempts:
2 left
💡 Hint
Check how class-validator handles nested validation.
🧠 Conceptual
expert
2:00remaining
What is the effect of setting forbidNonWhitelisted to true in ValidationPipe?
If you configure ValidationPipe with whitelist: true and forbidNonWhitelisted: true, what happens when the request body contains extra properties not in the DTO?
AThe request is rejected with HTTP 400 and an error listing the extra properties.
BThe extra properties are silently removed and the request proceeds.
CThe server logs a warning but processes the request normally.
DThe extra properties are added to the DTO instance.
Attempts:
2 left
💡 Hint
Think about how forbidNonWhitelisted changes whitelist behavior.

Practice

(1/5)
1. What is the main purpose of using ValidationPipe in a NestJS application?
easy
A. To serve static files like images and CSS
B. To handle database connections automatically
C. To check and clean incoming data to ensure it is safe and correct
D. To manage user authentication and authorization

Solution

  1. Step 1: Understand ValidationPipe role

    ValidationPipe is designed to validate and sanitize incoming data in NestJS, ensuring the data meets expected rules.
  2. Step 2: Compare with other options

    Other options like database handling, authentication, or serving static files are unrelated to ValidationPipe's purpose.
  3. Final Answer:

    To check and clean incoming data to ensure it is safe and correct -> Option C
  4. Quick Check:

    ValidationPipe purpose = data validation and cleaning [OK]
Hint: ValidationPipe is all about checking incoming data [OK]
Common Mistakes:
  • Confusing ValidationPipe with authentication features
  • Thinking ValidationPipe manages database connections
  • Assuming ValidationPipe serves static files
2. Which is the correct way to apply ValidationPipe globally in a NestJS app inside main.ts?
easy
A. app.useGlobalPipes(new ValidationPipe())
B. app.usePipes(new ValidationPipe())
C. app.setGlobalPipes(new ValidationPipe())
D. app.applyGlobalPipes(new ValidationPipe())

Solution

  1. Step 1: Recall NestJS global pipe method

    The official method to set global pipes is app.useGlobalPipes().
  2. Step 2: Check other options

    Methods like usePipes, setGlobalPipes, or applyGlobalPipes do not exist or are incorrect.
  3. Final Answer:

    app.useGlobalPipes(new ValidationPipe()) -> Option A
  4. Quick Check:

    Global pipe setup = useGlobalPipes() [OK]
Hint: Global pipes use app.useGlobalPipes() [OK]
Common Mistakes:
  • Using non-existent methods like setGlobalPipes
  • Confusing useGlobalPipes with usePipes
  • Missing the 'new' keyword before ValidationPipe
3. Given this main.ts snippet, what will happen when a request sends extra properties not defined in the DTO?
app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
medium
A. The request will fail with a validation error
B. Extra properties will be removed from the incoming data
C. Extra properties will be kept without changes
D. The app will crash due to unknown properties

Solution

  1. Step 1: Understand whitelist option in ValidationPipe

    Setting whitelist: true removes any properties not defined in the DTO from the incoming data.
  2. Step 2: Check behavior on extra properties

    With whitelist true, extra properties are stripped, not causing errors or crashes.
  3. Final Answer:

    Extra properties will be removed from the incoming data -> Option B
  4. Quick Check:

    whitelist true = remove extra props [OK]
Hint: whitelist true strips unknown properties [OK]
Common Mistakes:
  • Thinking whitelist causes validation errors on extra props
  • Assuming extra props are kept unchanged
  • Believing app crashes on extra properties
4. What is wrong with this main.ts code snippet for setting up ValidationPipe globally?
app.useGlobalPipes(ValidationPipe({ transform: true }));
medium
A. Missing 'new' keyword before ValidationPipe
B. The 'transform' option is invalid
C. useGlobalPipes should be called inside a controller
D. ValidationPipe cannot be used globally

Solution

  1. Step 1: Check ValidationPipe instantiation

    ValidationPipe is a class and must be instantiated with the new keyword.
  2. Step 2: Validate other parts

    The transform option is valid, and useGlobalPipes is correctly used in main.ts.
  3. Final Answer:

    Missing 'new' keyword before ValidationPipe -> Option A
  4. Quick Check:

    Instantiate ValidationPipe with new [OK]
Hint: Always use 'new' with ValidationPipe class [OK]
Common Mistakes:
  • Omitting 'new' keyword when creating ValidationPipe
  • Thinking transform option is invalid
  • Trying to set global pipes inside controllers
5. You want to automatically convert incoming JSON strings to their expected types in your DTOs. Which ValidationPipe option should you enable globally to achieve this?
hard
A. forbidNonWhitelisted: true
B. whitelist: true
C. disableErrorMessages: true
D. transform: true

Solution

  1. Step 1: Understand transform option

    Setting transform: true tells ValidationPipe to convert incoming payloads to the types defined in DTO classes automatically.
  2. Step 2: Check other options

    whitelist removes extra properties, forbidNonWhitelisted throws errors on extra props, and disableErrorMessages hides validation errors; none convert types.
  3. Final Answer:

    transform: true -> Option D
  4. Quick Check:

    transform true = auto type conversion [OK]
Hint: Use transform true to convert types automatically [OK]
Common Mistakes:
  • Confusing whitelist with type conversion
  • Thinking forbidNonWhitelisted converts types
  • Believing disableErrorMessages affects data types
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard