Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single resource file for DataAnnotations localization

What I should try to achieve is to have a single resource (resx) file for each supported language in net-core. I explain the problem a bit.

I have DataAnnotations on each of my entities and I need to localize the messages returned in case of errors. It seems that the default convention required by net-core is to have a different resx file for each of our entities.

This file is named accordingly to the namespace of the entity with the culture indentifier and the resx extensions. So, if I have an entity named Customers within the namespace Data.Entities, I should add a file named Data.Entities.Customers.it.resx and put all the translations for the Italian language in it. So, if I have an attribute

StringLength(50, ErrorMessage="The {0} should not be longer than {1} characters") 
public string Name {get;set;}

then I add the proper translation to the Data.Entities.Customers.it.resx file.

But, if I go on another entitity like Suppliers I am forced to write another resource file named Data.Entities.Suppliers.it.resx and, of course I have

StringLength(50, ErrorMessage="The {0} should not be longer than {1} characters") 
public string SupplierName {get;set;}

Now I need to write again the same translation in the proper file for the Suppliers entity. This goes on as well for other common attributes like [Required].

So I hope to have explained well my problem and my queston is: There is a way to specify a single resource file for all my entities validation messages and then write a single time the messages for the common texts?

like image 835
Steve Avatar asked Oct 30 '22 04:10

Steve


1 Answers

From the docs, you can tell the framework to use a shared resource for your data annotations localisation:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddDataAnnotationsLocalization(options => {
            options.DataAnnotationLocalizerProvider = (type, factory) =>
                factory.Create(typeof(SharedResource));
        });
}

In the preceeding code, SharedResource is the class corresponding to the resx where your validation messages are stored. With this approach, DataAnnotations will only use SharedResource, rather than the resource for each class.

like image 104
DavidG Avatar answered Nov 09 '22 15:11

DavidG