Search code examples
validationasp.net-corelocalizationresourcesglobalization

Localization on data annotation and error validation messages in ASP.NET CORE 3.1


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://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-3.1#dataannotations-localization] Please someone help me


Solution

  • 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 .