我正在构建一个带有 NestJS 后端和 Next.js 前端的 Web 应用程序。对于本地化和翻译,我在前端使用“next-i18next”库,对于验证和错误处理,我使用 NestJS 的类验证器和其他错误消息。
错误示例:
username must be a string
、username should not be empty
、username must be longer than or equal to 10 characters
我的后端目前以单一语言提供错误消息,包括验证错误消息。在前端,我想以多种语言显示这些错误消息,以提供更好的用户体验。
具体来说,我使用类验证器进行验证,并且需要翻译这些验证错误消息。此外,我想处理后端生成的其他错误消息的翻译。
如何在前端有效地翻译这些错误消息,同时保持后端错误处理完整?使用“next-i18next”进行本地化时,处理 NestJS(后端)和 Next.js(前端)之间不同语言的错误消息(包括验证错误)的最佳方法是什么?
我非常感谢有关如何有效实施此解决方案的任何指导或代码示例。
很好的问题,这是我如何使用类验证器为 NestJs 验证执行自定义消息。
// Your validation class. Note that we are sending a METHOD as the message
export class PostEntryDto {
@ApiProperty({ description: 'Api Key' })
@IsString({ message: stringValidationMessage })
readonly apiKey: string;
}
export const stringValidationMessage = (args: ValidationArguments): string => {
return `${capitalize(args.property)} must be a string`; // Use i18n in here to make things smoother for you.
};
这里唯一要记住的是始终使用消息键发送 @IsXXXX() 内的函数。
查看
ValidationArguments
类型,您还可以在那里提取更多内容,例如 value
,以便在自定义消息中使用。
希望这有帮助!