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

How to remove Field Name in custom message in class-validator NestJS

1个答案

1

In NestJS, when using class-validator for data validation, by default, error messages include the specific field name. For example, if a validation rule for a field named username fails, it may return an error message such as: 'username must be longer than or equal to 10 characters'.

If you wish to exclude the field name from custom validation messages, you can achieve this by customizing error messages to omit the field name. This can be done by using string templates within decorators. For example, consider the following user class using class-validator:

typescript
import { IsLength, IsEmail } from 'class-validator'; export class CreateUserDto { @IsLength(10, 20, { message: 'The length must be between 10 and 20 characters' }) username: string; @IsEmail({}, { message: 'The provided value must be a valid email address' }) email: string; }

In the above example, we customize the error message to exclude the field name. Thus, when the username length is invalid or the email format is incorrect, the error message will only display 'The length must be between 10 and 20 characters' and 'The provided value must be a valid email address', without showing the field name.

Additionally, if you need further customization or dynamic generation of error messages (e.g., based on different language environments), consider using custom validation decorators or the callback function feature of class-validator to generate error messages. This enables more complex and dynamic validation logic.

For example, create a custom validator to check if a string contains a specific character without including the field name in the message:

typescript
import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator'; function ContainsLetter(letter: string, validationOptions?: ValidationOptions) { return function (object: any, propertyName: string) { registerDecorator({ name: 'containsLetter', target: object.constructor, propertyName: propertyName, constraints: [letter], options: validationOptions, validator: { validate(value: any, args: ValidationArguments) { const [relatedLetter] = args.constraints; return typeof value === 'string' && value.includes(relatedLetter); }, defaultMessage(args: ValidationArguments) { return `Must contain the letter ${args.constraints[0]}`; } } }); }; } // Usage class SomeClass { @ContainsLetter('x', { message: 'Must contain the letter x' }) myField: string; }

Thus, when myField does not contain the letter 'x', the error message will only display 'Must contain the letter x', without mentioning myField. This approach offers greater flexibility and control, allowing for free customization based on requirements in practical applications.

2024年8月24日 17:33 回复

你的答案