Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringLengh Data Annotation using a static property

I'd like to use the StringLength Attribute on an Entity, but instead of using a literal or a constant, to use a static property.

e.g

[StringLength(MyClass.MyStaticProperty)]
public string Code { get; set; }

However this results in the following error...

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

... has anyone got a work around or an alternative, other than using a string literal or constant?

In case you're wondering why a static property? The static property will return a value from an injected singleton. The value will be injected at startup of the application.

Thanks... and Merry Christmas...

like image 955
Mick Avatar asked Jan 23 '26 09:01

Mick


2 Answers

Creating your own attribute is probably the best solution. You can then also take control over any other logic you might want to implement later.

public class CustomStringLength: ValidationAttribute
{
    public CustomStringLength()
    {
    }

    public override bool IsValid(object value)
    {
        return (string)value.Length == MyClass.MyStaticProperty;
    }
}

Considering MyClass.MyStaticProperty is an int.

Usage:

[CustomStringLength]
public string Code { get; set; }
like image 145
Dion V. Avatar answered Jan 25 '26 23:01

Dion V.


StringLength attribute parameter should be known at compile time.

You can either specify the exact value or refer to a constant value:

public static class MyClass
{
    public const int MyStaticProperty = 5;
}

[StringLength(MyClass.MyStaticProperty)]
public string Code { get; set; }

Note that there is no static keyword, since const implies static.

like image 33
Yeldar Kurmangaliyev Avatar answered Jan 25 '26 23:01

Yeldar Kurmangaliyev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!