How localize ErrorMessage in DataAnnotation?

Viewed 8875

Using MVC 5 I need to localize an ErrorMessage for a DataAnnotation attributes. I receive the following error

ERROR

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

In model

[Compare("Password", ErrorMessage = Resources.Account_Register_ConfirmPasswordErrorMessage)]
public string ConfirmPassword { get; set; }

Any idea how to fix it?

3 Answers

Here's a detailed explanation on how to do this:

You add appropriate culture resx files to conventional folders, and tell the DA engine to look through them:

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

So for this model:

public class RegisterViewModel
{
    [Required(ErrorMessage = "The Email field is required.")]
    [EmailAddress(ErrorMessage = "The Email field is not a valid email address.")]
    [Display(Name = "Email")]
    public string Email { get; set; }
}

You'd add a resx file in one of the following locations:

  • Resources/ViewModels.Account.RegisterViewModel.fr.resx
  • Resources/ViewModels/Account/RegisterViewModel.fr.resx

For non-ASP.NET environments such as WPF, WinForms or others, see this answer.

Related