user3212730
user3212730

Reputation: 373

range restriction to attributes, DateTime

I'm trying to make restriction based on a range of value given to a date value, using this :

[Range(typeof(DateTime), "1/1/1971", DateTime.Now.AddDays(1).ToString())]
public DateTime date { get; set; }

But, I got an error saying that I cannot use variables into that restriction. How can I achieve that, please ?

Thanks in advance !

Upvotes: 1

Views: 861

Answers (2)

Andrei V
Andrei V

Reputation: 7506

Since the Attributes expect constant values, you would have to implement your custom metadata provider. You would then inject the end value of your range dynamically.

public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
     protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
     {
          base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

          foreach (var attribute in attributes.OfType<RangeAttribute>())
          {
               if (attribute.OperandType == typeof(DateTime)
               {
                    attribute.Maximum = DateTime.Now.AddDays(1).ToString();
               }
          }
     }
}

Another option, as suggested in Abbas' answer is to create a custom validation attribute. Something along these lines:

public class CustomDateRangeAttribute : RangeAttribute
{
     public CustomDateRangeAttribute()
     {
          base();
          base.Maximum = DateTime.Now.AddDays(1).ToString();
     }
}

Upvotes: 1

Abbas
Abbas

Reputation: 14432

Although it is not specified in the RangeAttribute Class or RangeAttribute Constructor (Type, String, String) documentation, the constructor expects constant values.

Upvotes: 0

Related Questions