How to add localization for default data annotations validation error messages in ASP.NET Core 6 MVC?

48 Views Asked by At

The idea is to make use of the default messages for fast development of apps and for cleaner code, but I couldn't figure out a way to do it.

This is how far I got:

// Program.cs:
using ...
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddLocalization(o => o.ResourcesPath = "Resources");
builder.Services.AddControllersWithViews()
    .AddDataAnnotationsLocalization(o => {
        o.DataAnnotationLocalizerProvider = (type, factory) =>
        {
            var assemblyName = new AssemblyName(typeof(SharedResources).GetTypeInfo().Assembly.FullName!);
            return factory.Create("SharedResources", assemblyName.Name!);
        };
    });
...
var app = builder.Build();
...
var supportedCultures = new[] { "en-US", "es-CL" };
var localizationOptions = new RequestLocalizationOptions()
    .SetDefaultCulture("es-CL")
    .AddSupportedCultures(supportedCultures)
    .AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(localizationOptions);
...
app.Run();

And the model:

namespace WebApplication1.Models
{
    public class Cliente
    {
        public int Id { get; set; }

        [Required]
        [StringLength(100)]
        public string Nombre { get; set; } = null!;

        [StringLength(100)]
        public string? Apellido { get; set; }

        [EmailAddress]
        public string? Email { get; set; }

        [Phone]
        public string? Telefono { get; set; }
    }
}

With the resources files I tried a bunch of different keys but none works:

// SharedResources.cs:
public class SharedResources { /* empty class */ }

// SharedResources.en-US.resx:
"Required"                          "The {0} field is required."
"RequiredAttribute"                 "The {0} field is required."
"RequiredAttribute_ValidationError" "The {0} field is required."
"The {0} field is required."        "The {0} field is required."
"The0FieldIsRequired"               "The {0} field is required."
"TheFieldIsRequired"                "The {0} field is required."

// SharedResources.es-CL.resx:
"Required"                          "El campo {0} es requerido."
"RequiredAttribute"                 "El campo {0} es requerido."
"RequiredAttribute_ValidationError" "El campo {0} es requerido."
"The {0} field is required."        "El campo {0} es requerido."
"The0FieldIsRequired"               "El campo {0} es requerido."
"TheFieldIsRequired"                "El campo {0} es requerido."

It only works if I declare the attribute like this:

[Required(ErrorMessage = "The {0} field is required.")]

But I need to declare it like the following for fast development and cleaner code:

[Required]
1

There are 1 best solutions below

4
Tiny Wang On

I'm afraid your requirement can't be implemented.

We have a document here which mentioned If the localized value of "About Title" isn't found, then the indexer key is returned, that is, the string "About Title". and I think this means we require a key to search in the resource file to get a replacement as a response.

I test in my side with your code snippet, and I found it I used [Required(ErrorMessage = "Required")], then the output would be the desired localized content.

enter image description here

Since we couldn't leave the Name column to be empty, so I'm afraid we have to define a "key" then use this key in Data annotation to make it work.

enter image description here