You can not pass a non-constant value to an attribute, so your solution can not be implemented.
However, you can pass a const
value from config file. If you are accepting behaviour like the following: validation of the string will be of single maximum length for a whole lifetime of application and to change it you should reboot an app, take a look at variables in application config.
If you does not accept this behaviour, the one of possible solutions is to store your MaxLength
somewhere in database and create your own StringLengthAttribute
, which will query DB (or another data source) during valigation in the following way:
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
sealed class MyValidationAttribute : ValidationAttribute
{
public MyValidationAttribute()
{
}
public override bool IsValid(object value)
{
if (value != null && value.GetType() == typeof(string))
{
int maxLength = //query your data source
return ((string)value).Length <= maxLength;
}
return base.IsValid(value);
}
}
Another possible solution is to perform client-side validation instead of server-side. If you will query your data source from the client-side it will look better, than querying it from attribute, in my opinion.