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

How to set custom error message IsEnum of class-validator in nestjs

1个答案

1

When using class-validator in NestJS to set custom error messages, you can customize the error message for the IsEnum validator by passing an options object. Here's a concrete example demonstrating how to implement this:

First, ensure your project has installed the class-validator and class-transformer libraries. If not, install them using the following command:

bash
npm install class-validator class-transformer

Then, in your DTO (Data Transfer Object), you need to define an enum type and a field using this enum type, as shown below:

typescript
import { IsEnum } from 'class-validator'; enum UserRole { Admin = 'admin', Editor = 'editor', Subscriber = 'subscriber' } export class CreateUserDto { @IsEnum(UserRole, { message: 'role must be one of the following values: $constraint1' }) role: UserRole; }

In the above code, we define an enum named UserRole that contains three possible roles. In the CreateUserDto class, the role field is annotated with @IsEnum. In the IsEnum decorator, we pass a configuration object where the message property is set to a custom error message. $constraint1 is a special placeholder that is replaced in the error message with the allowed values of the UserRole enum received by the IsEnum decorator.

When attempting to create a CreateUserDto instance with a role field value not present in the UserRole enum, a validation error will be thrown, and the error message will be our custom message.

This approach provides a flexible way to provide more specific error information, helping developers and end-users better understand the specific reasons for data validation failures.

2024年7月24日 10:00 回复

你的答案