views:

260

answers:

3

I am playing around with the System.ComponentModel.DataAnnotations namespace, with a view to getting some validation going on my ASP.NET MVC application.

I have already hit an issue with the RegularExpression annotation.

Because these annotations are attributes they require constant expressions.

OK, I can use a class filled with regex string constants.

The problem with that is I don't want to pollute my regex with escape characters required for the C# parser. My preference is to store the regex in a resources file.

The problem is I cant use those string resources in my data annotations, because they are not constants!

Is there any solution to this?

If not, this seems a significant limitation of using attributes for validation.

+3  A: 

In C# there is only one escape code you need (double-quote)... if you use verbatim string literals:

@"like \this\ note \slash here does nothing only quote "" needs doubling
you can even use newline";

I always write regex with @"..." strings - avoids many headaches.

Marc Gravell
A: 

Apparently in .NET 4 there are overrides for the DataAnnotations attribubtes that take a Func< string> in their constructor described as "The function that enables access to validation resources."

Schneider
A: 

You could create a custom validation attribute like this as a proxy which would load the regular expressions from your resource file.

minimalis