2015-03-03 49 views
0

参照这个线程stackoverflowMVC模型的日期范围注释动态日期

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

我想一些动态日期添加到我的模型的日期范围验证为:

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;} 

但发生错误。是否没有办法在MVC中设置动态日期范围验证?

+0

你不能。验证属性只接受静态值/常量。 – 2015-03-03 08:01:52

+0

一个选项是在模型中包含其他'DateTime'属性(用于最小值和最大值)并使用[foolproof](http://foolproof.codeplex.com/)'[GreaterThan]'和[[LessThan] '验证属性 – 2015-03-03 08:06:32

+0

万无一失是有用的..谢谢 – 2015-03-03 08:14:29

回答

2

您不能在属性中使用动态值,因为它们是在编译时生成的元数据。实现这一目标的一种可能性是编写自定义验证属性或使用Fluent Validation,它允许使用流畅表达式表达更复杂的验证方案。

这里有这样的自定义验证属性如何可能看起来像一个例子:

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)); 
    } 
} 

,然后用它装点你的模型:

[MyValidation(6)] 
public DateTime EventOccurDate { get; set; }