Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ASP.NET Core model errors in a specific language other than english

I use DataAnnotation for validating models in ASP.NET Core. But when I have a required field, I got the error message in english when its missing like in this example:

class MyModel {
    [Required]
    [Display(Name = "Seitentitel")]
    public string Title {get;set;}
}

This gave me a denglish the validation error message The Seitentitel field is required. But I want to have the message in a specific language, in this case for german. I would like to avoid setting the ErrorMessage for each required attribute of my model. The default error message is fine in most cases, but in the wrong language.

How can I set the language for those validation messages?

I tried this one without success:

var supportedCultures = new[] { new CultureInfo("de-DE") };
            app.UseRequestLocalization(new RequestLocalizationOptions {
                DefaultRequestCulture = new RequestCulture("de-DE"),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            });

If ASP.NET Core doesn't provide those translation, I need something like this: https://stackoverflow.com/a/38199890/5426333 But not for ASP.NET Core Identity, instead for the generic validation messages like in this case when a required-field is missing.

like image 1000
Lion Avatar asked Nov 11 '16 15:11

Lion


1 Answers

I believe (may be wrong) that the language of the error messages depends on your install of .net. If you're getting english ones you would need to remove your .net version and install a German one.

You can set your default lang in the web config, such as (if this doesnt change the lang of the message then you will need resx files or hard-code them on your attributes:

<system.web>
   <globalization uiCulture="de-DE" />
</system.web>

If not in the web.config then you would change the uiculture in the global.asax file for each request.

In any other case, You should use Resource files. *.resx to store the text you want to display.

You may need to read a little about these; unsure of your experience with them. If so, a good place to start would be Walkthrough: Using Resources for Localization with ASP.NET Essentially they are key/value pairs. You have a file per language.

Then in your attributes you would do something like this:

 [Required(ErrorMessageResourceName = "MyResourceKey", ErrorMessageResourceType = typeof(Your.Namespace.To.your.Resource.File))]
 public string SomeString{ get; set; }

Then no matter what language you are presenting at runtime (based on what resource files you have setup) the appropriate version will be displayed.

like image 194
Darren Wainwright Avatar answered Sep 22 '22 14:09

Darren Wainwright