In NestJS, parameter validation is commonly handled by the class-validator library. This library provides decorators for defining validation rules for data. To validate that a parameter is not empty, use the @IsNotEmpty decorator.
Here is an example of how to use the @IsNotEmpty decorator to validate required parameters. First, ensure that you have installed the class-validator and class-transformer packages.
bashnpm install class-validator class-transformer
Then, use the decorators when defining parameters in your DTO (Data Transfer Object):
typescriptimport { IsNotEmpty } from 'class-validator'; export class CreateUserDto { @IsNotEmpty() username: string; @IsNotEmpty() password: string; }
In this example, the CreateUserDto class is used to pass the data required for creating a new user. username and password are both decorated with @IsNotEmpty, indicating that these fields must not be empty during request processing.
Now, let's look at a specific controller method that uses CreateUserDto to receive data:
typescriptimport { Body, Controller, Post } from '@nestjs/common'; import { CreateUserDto } from './create-user.dto'; @Controller('users') export class UsersController { @Post() async create(@Body() createUserDto: CreateUserDto) { // Here is your business logic, for example, saving user information to the database } }
To make parameter validation effective, you need to enable the global pipeline in the main.ts file (or your application entry file). NestJS provides an internal ValidationPipe that automatically applies the validation rules defined in class-validator.
typescriptimport { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ValidationPipe } from '@nestjs/common'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe()); await app.listen(3000); } bootstrap();
Using ValidationPipe, when a client sends a request containing empty username or password, NestJS throws a BadRequestException and returns a response indicating which fields do not meet the validation criteria. This process ensures that only validated data is processed by the controller.