乐闻世界logo
搜索文章和话题

How do you implement custom validation logic for DTOs in Nest.js?

1个答案

1

To implement custom validation logic for DTOs in Nest.js, we typically use the class-validator library, which provides decorators and functions to define these validation rules. Here are some steps and examples to implement custom validation logic:

Step 1: Install Dependencies

First, ensure your project has the class-validator and class-transformer packages installed.

bash
npm install class-validator class-transformer

Step 2: Define DTO

Use decorators in your DTO to define validation rules. For example, let's define a CreateUserDto:

typescript
import { IsNotEmpty, IsEmail, Validate } from 'class-validator'; export class CreateUserDto { @IsNotEmpty() name: string; @IsEmail() email: string; @IsNotEmpty() password: string; @Validate(CustomPasswordValidator) password: string; }

Step 3: Create a Custom Validator

To add custom validation logic, create a custom validator class. For example, let's implement a validator for password complexity:

typescript
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator'; @ValidatorConstraint({ name: 'customPasswordValidator', async: false }) export class CustomPasswordValidator implements ValidatorConstraintInterface { validate(password: string, args: ValidationArguments) { // Password must be at least 8 characters long and include at least one number, one uppercase letter, and one lowercase letter return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/.test(password); } defaultMessage(args: ValidationArguments) { // Custom message when validation fails return 'Password must be at least 8 characters long and contain at least one number, one uppercase letter, and one lowercase letter.'; } }

Step 4: Use DTO in Controller

Ensure you use this DTO in your controller and leverage Nest.js's pipes to automatically apply validation.

typescript
import { Body, Controller, Post } from '@nestjs/common'; import { CreateUserDto } from './create-user.dto'; @Controller('users') export class UsersController { @Post() async create(@Body() createUserDto: CreateUserDto) { // The createUserDto object is validated before reaching this point // If validation fails, Nest.js automatically throws an exception return 'User created successfully'; } }

Summary

Through these steps, we demonstrate how to implement custom DTO validation logic in a Nest.js project. By using the @Validate decorator from class-validator, you can easily add complex custom validation logic to meet business requirements. This ensures the data integrity and security of your application.

2024年7月31日 00:50 回复

你的答案