Ways to share regex across DataAnnotations /Attributes
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.
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.
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."
You could create a custom validation attribute like this as a proxy which would load the regular expressions from your resource file.
精彩评论