Why can't I use resources as ErrorMessage with DataAnnotations?

Johan Alkstål picture Johan Alkstål · Apr 22, 2010 · Viewed 25.1k times · Source

Why can't I do like this?

[Required(ErrorMessage = "*")]
[RegularExpression("^[a-zA-Z0-9_]*$", ErrorMessage = Resources.RegistrationModel.UsernameError)]
public string Username { get; set; }

What is the error message telling me?

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

Answer

AxelEckenberger picture AxelEckenberger · Apr 22, 2010

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).

Setting resource access to public