views:

64

answers:

2

I would like to add a regular expression to a nattribute from a static class.

[RegularExpression(MyRegex.DecimalRegEx)]

from a class:

 public static class MyRegex
    {        
        public static string Decimal_Between_1_And_100
        {
            get
            {
                return (@"^\s*\d+(\.\d{1,2})?\s*$");           
            }
        }        
    }

I know the attribute needs a const val - is there no way round this?

thanks

Davy

+2  A: 

It is not possible to add an instance of Regex to an attribute because as you said, attribute arguments must be constant values. There is no way to work around this limitation as it's a limitation of the CLR / CLI.

The best you can do is take string values which are converted to Regex's under the hood inside the attribute constructor.

public class RegularExpressionAttribute : Attribute {
  public readonly string StringValue;
  public readonly Regex Regex;
  public RegularExpressionAttribute(string str) {
    StringValue = str;
    Regex = new Regex(str);
  }
}
JaredPar
A: 

You can assign the MyRegEx class type instead of the instance of the regex, here is the idea below.

public interface IRegexProvider
{
    Regex Regex { get; }
}

public class RegularExpressionAttribute : Attribute 
{
    public readonly Type _factory;

    public RegularExpressionAttribute(Type regexFactory)
    {
        _factory = regexFactory;
    }

    public Regex Regex
    {
        get
        {
            // you can cache this
            var factory = (IRegexProvider)Activator.CreateInstance(_factory);
            return factory.Regex;
        }
    }
}


// using

public class MyRegex : IRegexProvider
{        
    public Regex Regex
    {
        get
        {
            return new Regex(@"^\s*\d+(\.\d{1,2})?\s*$");           
        }
    }        
}

[RegularExpression(typeof(MyRegex))]
Shay Erlichmen
Thanks - have you tried this? It doesn't compile - cannot assign attribute to generic type?
Davy
I have't tired to compile it (didn't have VS available) it is fixed now. The version above compiles now.
Shay Erlichmen
Thanks shay - I should have posted this earlier but I' mtrying to use this with DataAnnotations also, is there any way to use this istead of the one that expects a string? - sry very new to this.
Davy