How localize ErrorMessage in DataAnnotation?

2020-04-03 01:52发布

问题:

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?

回答1:

You need to use ErrorMessageResourceName and ErrorMessageResourceType properties.

For example like this:

[Compare("Password", ErrorMessageResourceName = "ConfirmPasswordErrorMessage",
  ErrorMessageResourceType=typeof(<<type_of_your_resoruce_class>>)]
public string ConfirmPassword { get; set; }

Hope this helps!

Regards, Uros



回答2:

You don't need anything, just create your resource file in right place.

For example Resources > ViewModels > LoginVm.ka-GE.resx (Georgian culture-info)

in LoginVm:
[Required(ErrorMessage = "UserName is Required")]

and in LoginVm.ka-GE.resx just add

UserName is Required > სახელი არის აუცილებელი < (it's Georgian Language)

and all done.



回答3:

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.