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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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
Method 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.
Method 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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0