2
votes

How to localize data annotation and validation error messages in ASP.NET CORE 3.1

[Required(ErrorMessage = "something")]
                [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
                [DataType(DataType.Password)]
                [Display(Name = "Password")]
                public string Password { get; set; }

I use the standard implementation of resource files from the Microsoft documentation

services.AddLocalization(option => option.ResourcesPath = ProjectConstants.LanguageResourcesPath);

        services.AddControllersWithViews()
                .AddViewLocalization(
                    LanguageViewLocationExpanderFormat.Suffix,
                      option => option.ResourcesPath = "Resources")
                .AddDataAnnotationsLocalization();

My Resource Files structure

|-Resoures
|---Controllers
|---Views
|---Models

I am refactoring Identity Pages and can not showing standard error messages in two languages. This example in Microsoft docs does not work for me.. [https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-3.1#dataannotations-localization] Please someone help me

1
Where is your model?Make sure the naming of resource file is correct.You could set LogLevel to Debug in appsettings.Development.json and check the log when you submit the form. - Ryan
In addition to @XingZou answer, This tutorial and repository can help do localization faster. - LazZiya
Hi, there was a problem naming the resource and I found it, but it came up big. I get an error when I try to make the resource public "InvalidOperationException: Cannot retrieve property 'Name' because localization failed." And also I get an error in Visual Studio for resxcodegenerator "PublicResXFileCodeGenerator failed to produce an output for input file 'Resource.en-US.resx' but did not log a specific error." I tried my best and I can't fix it, has anyone encountered this problem? - Валентин Стоев

1 Answers

4
votes

For adding DataAnnotations localization on InputModel in default Identity Register Pages(located in /Areas/Identity/Pages/Account/Register.cshtml.cs),you need to name your resource file like

Areas.Identity.Pages.Account.RegisterModel+InputModel.en-US.resx

For any nested model in PageModel, you need to use + instead of .