Why can't I use resources as ErrorMessage with DataAnnotations?
When you are using the ErrorMessage
property only constant strings or string literal can be assigned to it.
Use the ErrorMessageResourceType
and ErrorMessageResourceName
instead to specity your resources.
[RegularExpression(
"^[a-zA-Z0-9_]*$",
ErrorMessageResourceType=typeof(Resources.RegistrationModel),
ErrorMessageResourceName= "UsernameError"
)]
Note that the resources must be public (can be set in the resource editor).
Please see this link: http://code.msdn.microsoft.com/Getting-Started-WCF-RIA-1469cbe2/sourcecode?fileId=19242&pathId=774666288 (link broken, but left for attribution purposes)
public sealed partial class RegistrationData
{
[Key]
[Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ErrorResources))]
[Display(Order = 0, Name = "UserNameLabel", ResourceType = typeof(RegistrationDataResources))]
[RegularExpression("^[a-zA-Z0-9_]*$", ErrorMessageResourceName = "ValidationErrorInvalidUserName", ErrorMessageResourceType = typeof(ErrorResources))]
[StringLength(255, MinimumLength = 4, ErrorMessageResourceName = "ValidationErrorBadUserNameLength", ErrorMessageResourceType = typeof(ErrorResources))]
public string UserName { get; set; }