Перейти к содержанию

Валидация данных

The ValidationPipe is a built-in pipe that can be used to validate data coming from the client. It uses class-validator package under the hood. The ValidationPipe provides a convenient approach to enforce validation rules for all incoming client payloads, where the specific rules are declared with simple annotations in DTO declarations in each module.

Установка

$ npm install class-validator class-transformer

Использование

Now we can add a few validation rules in our CreateUserDto. We do this using decorators provided by the class-validator package, described in detail here. In this fashion, any route that uses the CreateUserDto will automatically enforce these validation rules.

src/users/dto/create-user.dto.ts
import { IsEmail, IsNotEmpty, IsOptional, IsString } from 'class-validator';
import { StringOption } from 'necord';

export class CreateUserDto {
@IsString()
@IsNotEmpty()
@StringOption({
name: 'name',
description: 'Your name',
required: true
})
public readonly name!: string;

@IsOptional()
@IsEmail()
@StringOption({
name: 'email',
description: 'Your email',
required: false
})
public readonly email?: string;
}
совет

Also you can use ValidationPipe for transforming and validating the payload of a request.

Read more about transforming

Now, we can use the ValidationPipe in our UsersCommands to enforce the validation rules we just defined.

src/users/users.commands.ts
import { Injectable, ValidationPipe } from '@nestjs/common';
import { Context, Options, SlashCommand, SlashCommandContext } from 'necord';
import { CreateUserDto } from './dto/create-user.dto';

@Injectable()
export class UsersCommands {
@SlashCommand({
name: 'create',
description: 'Create a new user'
})
public async onCreateUser(
@Context() [interaction]: SlashCommandContext,
@Options(new ValidationPipe({ validateCustomDecorators: true })) createUserDto: CreateUserDto
): Promise<void> {
await interaction.reply({ content: `User created: ${createUserDto.name}` });
}
}

Now, if we try to use the create command without providing a name, or provide an invalid email, we will get an error message.

{"statusCode":400,"message":["email must be an email"],"error":"Bad Request"}

You can create snippet for validated options decorator:

src/decorators/validated-options.decorator.ts
import { PipeTransform, Type, ValidationPipe } from '@nestjs/common';
import { Options } from 'necord';

export const ValidatedOptions = (
...pipes: Array<PipeTransform | Type<PipeTransform>>
) => Options(...pipes, new ValidationPipe({ validateCustomDecorators: true }));
совет

You can create filters to handle and response validation errors.

See Exception Filters for more information