NestJS typically uses the class-validator and class-transformer libraries for parameter validation. class-validator allows us to define validation rules on classes using decorators, while class-transformer converts plain objects into class instances, enabling class-validator to apply these rules.
For validating optional parameters, we can use the decorators provided by class-validator and specify parameters as optional by passing options. Here's an example of how to validate optional parameters:
First, we need to install the necessary packages:
bashnpm install class-validator class-transformer
Then, define a DTO (Data Transfer Object) and use decorators to indicate which properties are optional:
typescriptimport { IsOptional, IsString, Length } from 'class-validator'; export class UpdateUserDto { @IsOptional() @IsString() @Length(2, 20) readonly name?: string; @IsOptional() @IsString() readonly bio?: string; }
In this example, the UpdateUserDto class defines two optional properties: name and bio. The @IsOptional() decorator indicates that the property is optional, meaning that if the property is absent in the input object or is null/undefined, class-validator will skip subsequent validation decorators.
In your controller, you can use the @Body decorator combined with ValidationPipe to automatically validate the incoming request body:
typescriptimport { Body, Controller, Post, UsePipes, ValidationPipe } from '@nestjs/common'; @Controller('users') export class UsersController { @Post('update') @UsePipes(new ValidationPipe({ skipMissingProperties: true })) async update(@Body() updateUserDto: UpdateUserDto) { // Update user logic } }
When skipMissingProperties is set to true in ValidationPipe, it only validates properties present in the DTO and ignores undefined properties. This way, even if optional parameters are not provided, the code will not throw errors due to validation failures.
Thus, NestJS can handle optional parameters flexibly while maintaining robust validation capabilities. If you need to validate specific properties even if they are not required, simply omit the @IsOptional() decorator on those properties.