2012-03-16 96 views
4

我wnat驗證日期時間,我的代碼是:MVC模型範圍驗證器?

[Range(typeof(DateTime), 
    DateTime.Now.AddYears(-65).ToShortDateString(), 
    DateTime.Now.AddYears(-18).ToShortDateString(), 
    ErrorMessage = "Value for {0} must be between {1} and {2}")] 
    public DateTime Birthday { get; set; } 

,但我得到的錯誤:

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

幫我嗎?

回答

11

這意味着Range屬性的值不能在稍後確定,它必須在編譯時確定。 DateTime.Now不是一個常量,它取決於代碼的運行時間。

你想要的是一個自定義的DataAnnotation驗證器。以下是如何建立一個例子:

How to create Custom Data Annotation Validators

把你的日期驗證邏輯的IsValid()

這裏的一個實現。我也使用DateTime.Subtract()而不是負數年份。

public class DateRangeAttribute : ValidationAttribute 
{ 
    public int FirstDateYears { get; set; } 
    public int SecondDateYears { get; set; } 

    public DateRangeAttribute() 
    { 
     FirstDateYears = 65; 
     SecondDateYears = 18; 
    } 

    public override bool IsValid(object value) 
    { 
     DateTime date = DateTime.Parse(value); // assuming it's in a parsable string format 

     if (date >= DateTime.Now.AddYears(-FirstDateYears)) && date <= DateTime.Now.AddYears(-SecondDateYears))) 
     { 
      return true; 
     } 

     return false; 
} 

}

用法爲:

[DateRange(ErrorMessage = "Must be between 18 and 65 years ago")] 
public DateTime Birthday { get; set; } 

這也是通用的,所以你可以在指定年新範圍值。

[DateRange(FirstDateYears = 20, SecondDateYears = 10, ErrorMessage = "Must be between 10 and 20 years ago")] 
public DateTime Birthday { get; set; }