views:

196

answers:

1

Hi,

I am currently using MVC 1.0 and .NET 3.5. I am using DataAnnotations to validate my model. I'm trying to add use the RegularExpression to validate a Postcode. I have stored my Regex in the resource file as many models will use it, when I try the following:

[RegularExpression(Resources.RegexPostcode, ErrorMessage="Postcode format invalid")]
public string Postcode { get; set; }

I get the following error when I build:

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

Is there any way to use values from a Resource file as the regex or will I need to enter the actual regex string into every model that has a postcode?

Thanks

+2  A: 

I would suggest making your own ValidationAttribute. This will keep the regex in one place as well as the error message.

class PostcodeAttribute : RegularExpressionAttribute
{
    public PostcodeAttribute() : base("your regex")
    {
        this.ErrorMessage = "Postcode format invalid";
    }
}
Jab