3

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

Fermin
  • 33,739
  • 20
  • 84
  • 127

2 Answers2

5

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
  • 13,673
  • 2
  • 41
  • 47
0

Can't leave a comment on the accepted answer as I don't have enough rep.

This accepted answer worked for me, but needed a tweak to work with the unobtrusive javascript validation. Needed the IClientValidatable bits from this answer: https://stackoverflow.com/a/18041534/1714585

Community
  • 1
  • 1
Bunjy
  • 120
  • 7