2

I have a multilanguage site running on ASP.NET Core 6 MVC.

The data annotation should be based on user language; I can make the site bilingual using sharedResource class.

The issue is how to make the model data annotation error bilingual; currently, I only got the data annotation ErrorMessage.

Program.cs

builder.Services.AddControllersWithViews()
             .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
              //.AddDataAnnotationsLocalization();// <--- for ERROR MSG -----
              .AddDataAnnotationsLocalization(
                 options => {
                     options.DataAnnotationLocalizerProvider = (type, factory) =>
                         factory.Create(typeof(DataAnnotationResource));
                 });// <---------- For ERROR MSG -----

FactoryData Model

public class FactoryData
{
    [Required(ErrorMessage = "General.RequiresMessageOOO")]
    public string NameInAr { get; set; }

    [Required(ErrorMessage = "General.RequiresMessageOOO")]
    [MaxLength(2, ErrorMessage = "General.MaxlengthExceededOOO")]
    public string NameInEn { get; set; }

    [Required]
    [Range(1,3)]
    public string Age { get; set; }
}

This is the localizationResource folder:

enter image description here

The output of this current code

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Eskander One
  • 103
  • 6
  • 13

2 Answers2

2

I ran into the same problem and I have to do these following changes

from

builder.Services.AddControllersWithViews()
    .AddDataAnnotationsLocalization(opt =>
    {
        opt.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResource));
    });

to

builder.Services.AddControllersWithViews()
.AddDataAnnotationsLocalization(opts =>
{
    opts.DataAnnotationLocalizerProvider = (type, factory) =>
    {
        var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName!);
        return factory.Create(nameof(SharedResource), assemblyName.Name!);
    };
});
0

You can use resources in DataAnnotations this way :

[Required(ErrorMessageResourceName = "General.RequiresMessageOOO", ErrorMessageResourceType = typeof(SharedResource))]
[MaxLength(2, ErrorMessageResourceName = "General.MaxlengthExceededOOO", ErrorMessageResourceType = typeof(SharedResource))]
public string NameInEn { get; set; }

and in your SharedResource.resx file :

<data name="General.RequiresMessageOOO" xml:space="preserve">
    <value>This field must not be empty</value>
</data>
<data name="General.MaxlengthExceededOOO" xml:space="preserve">
    <value>The value exceeded the max lenght</value>
</data>

In my application I have several SharedResource files for each language available :

Resources

You can get more detail about Localization in the Microsoft documentation here : Globalization and localization in ASP.NET Core

Gambi
  • 464
  • 4
  • 12