Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing a non-constant value in RangeAttribute?

When I do the following:

`[Range(1910, DateTime.Now.Year)]  
public int Year { get; set; }`

I get the following error:

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

Any ideas why?

like image 427
neebz Avatar asked Dec 17 '22 17:12

neebz


2 Answers

You could build for this a custom attribute something like RangeYearToCurrent in which you specify the current year

public class RangeYearToCurrent : RangeAttribute
{
    public RangYearToCurrent(int from)
        : base(typeof(int), from, DateTime.Today.Year) { }
}

untested...

like image 144
moi_meme Avatar answered Jan 05 '23 19:01

moi_meme


Here's my version, based on the previous answer (but working both client/server side):

 [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class RangeYearToCurrent : RangeAttribute,IClientValidatable { 
    public RangeYearToCurrent(int from) : base(from, DateTime.Today.Year) { }

    #region IClientValidatable Members

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rules = new ModelClientValidationRangeRule(this.ErrorMessage, this.Minimum, this.Maximum);
        yield return rules;
    }

    #endregion
}

Usage Exemple :

[RangeYearToCurrent(1995, ErrorMessage = "Invalid Date")]
public int? Year { get; set; }
like image 41
user726939 Avatar answered Jan 05 '23 20:01

user726939