1

with reference to this thread in stackoverflow

[Range(typeof(DateTime), "1/2/2004", "3/4/2004",
    ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime EventOccurDate{get;set;}

I tried to add some dynamic dates into my model's date range validator as:

private string currdate=DateTime.Now.ToString();
private string futuredate=DateTime.Now.AddMonths(6).ToString();

[Range(typeof(DateTime),currdate,futuredate,
    ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime EventOccurDate{get;set;}

But Error Occurs.Is there no way to set dynamic date range validation in MVC?

Community
  • 1
  • 1
Manoj Maximum
  • 43
  • 2
  • 8
  • You cant. Validation attributes only accept static values/constants. –  Mar 03 '15 at 08:01
  • An option is to include other `DateTime` properties in your model (for the min and max value) and use a [foolproof](http://foolproof.codeplex.com/) `[GreaterThan]` and `[LessThan]` validation attributes –  Mar 03 '15 at 08:06
  • foolproof is useful.. Thank you – Manoj Maximum Mar 03 '15 at 08:14

1 Answers1

4

You cannot use dynamic values in attributes because they are metadata that is generated at compile-time. One possibility to achieve this is to write a custom validation attribute or use Fluent Validation which allows for expressing more complex validation scenarios using a fluent expressions.

Here's an example of how such custom validation attribute might look like:

public class MyValidationAttribute: ValidationAttribute
{
    public MyValidationAttribute(int monthsSpan)
    {
        this.MonthsSpan = monthsSpan;
    }

    public int MonthsSpan { get; private set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            var date = (DateTime)value;
            var now = DateTime.Now;
            var futureDate = now.AddMonths(this.MonthsSpan);

            if (now <= date && date < futureDate)
            {
                return null;
            }
        }

        return new ValidationResult(this.FormatErrorMessage(this.ErrorMessage));
    }
}

and then decorate your model with it:

[MyValidation(6)]
public DateTime EventOccurDate { get; set; }
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928