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:
The output of this current code
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!);
};
});
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 :
You can get more detail about Localization in the Microsoft documentation here : Globalization and localization in ASP.NET Core
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With