Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How localize ErrorMessage in DataAnnotation?

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?

like image 371
GibboK Avatar asked Dec 20 '13 08:12

GibboK


People also ask

Which property of required data annotation is used to set the error message on validation?

ValidationAttribute, has an important property, ErrorMessage. This property get or set the custom validation message in case of error.

Which namespace is used for data annotation?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.


2 Answers

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

like image 176
Uroš Goljat Avatar answered Oct 28 '22 23:10

Uroš Goljat


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.

like image 26
Jorjini Avatar answered Oct 29 '22 01:10

Jorjini