Model validation error localization

I am working on an ASP.Net Core web application and should localize all the static strings that we use in the application.

I have a Controller and View string localized by implementing IStringLocalizerFactory and adding it as a service in Startup.cs.

Now I'm trying to add localization to model validation when using annotations. In my User model, I have

 [Required(ErrorMessageResourceType = typeof(UserModelErrorMessages), ErrorMessageResourceName = "FullNameRequired")] [MinLength(2, ErrorMessageResourceType = typeof(UserModelErrorMessages), ErrorMessageResourceName ="FullNameMinLength")] [MaxLength(100, ErrorMessageResourceType =typeof(UserModelErrorMessages), ErrorMessageResourceName ="FullNameMaxLength")] public string FullName { get; set; } 

I put "FullNameRequired", "FullNameMinLength", "FullNameMaxLength" in the file UserModelErrorMessage.resx. I also have a UserModelErrorMessage.fr.resx file with the same values ​​as the French equivalent messages. Correct error messages show when the browser is installed in English. When I switch my browser to French ('fr'), my static lines that I defined in the view and controller are displayed in French, but the data verification messages are still displayed in English. I tried Models.User.fr.resx and also generated .resource files manually, but to no avail.

In Startup.cs ConfigureServices:

 services.AddMvc() .AddViewLocalization(options=>options.ResourcesPath="Resources") .AddDataAnnotationsLocalization(); 

In Startup.cs - Configure

 app.UseRequestLocalization(new RequestLocalizationOptions { SupportedCultures = new List<CultureInfo> { new CultureInfo("fr"), new CultureInfo("zh"), new CultureInfo("tr"), new CultureInfo("en"), new CultureInfo("en-US"), }, SupportedUICultures = new List<CultureInfo> { new CultureInfo("fr"), new CultureInfo("zh"), new CultureInfo("tr"), new CultureInfo("en"), new CultureInfo("en-US"), } }, new RequestCulture("en-US") ); 

What am I missing to receive data annotation verification messages in French?

+5
source share

Source: https://habr.com/ru/post/1240627/


All Articles