2012-12-07 43 views
12

早些時候,我有一個視圖模型包含兩個日期時間的屬性我MVC4 Prject:C#屬性來檢查一個日期是否比其他

[Required] 
[DataType(DataType.Date)] 
public DateTime RentDate { get; set; } 

[Required] 
[DataType(DataType.Date)] 
public DateTime ReturnDate { get; set; } 

是否有使用C#屬性爲[Compare("someProperty")]檢查渡過一個簡單的方法RentDate屬性的值早於ReturnDate的值?

+1

你爲什麼要使用*屬性*?您希望什麼時候應用它?作爲驗證? –

+0

我相信應該通過驗證庫在客戶端驗證。然後,爲了安全起見,您可以在後端進行驗證,向模型狀態添加錯誤。 – TNCodeMonkey

+0

你爲什麼要比較?你的目的是限制一方的價值嗎?你可以嘗試搜索'強制',這就是它在WPF中的調用方式。不幸的是不能幫助你與asp.net。 –

回答

22

這裏是一個非常快的基本實現(沒有錯誤檢查等)這應該做你所問(只在服務器端......它不會做asp.net客戶端JavaScript驗證)。我沒有測試過,但應該足以讓你開始。

using System; 
using System.ComponentModel.DataAnnotations; 

namespace Test 
{ 
    [AttributeUsage(AttributeTargets.Property)] 
    public class DateGreaterThanAttribute : ValidationAttribute 
    { 
     public DateGreaterThanAttribute(string dateToCompareToFieldName) 
     { 
      DateToCompareToFieldName = dateToCompareToFieldName; 
     } 

     private string DateToCompareToFieldName { get; set; } 

     protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
     { 
      DateTime earlierDate = (DateTime)value; 

      DateTime laterDate = (DateTime)validationContext.ObjectType.GetProperty(DateToCompareToFieldName).GetValue(validationContext.ObjectInstance, null); 

      if (laterDate > earlierDate) 
      { 
       return ValidationResult.Success; 
      } 
      else 
      { 
       return new ValidationResult("Date is not later"); 
      } 
     } 
    } 


    public class TestClass 
    { 
     [DateGreaterThan("ReturnDate")] 
     public DateTime RentDate { get; set; } 

     public DateTime ReturnDate { get; set; } 
    } 
} 
+0

不錯的實施。 –

+0

這正是我正在尋找的,非常感謝! – cLar

3

它看起來像你使用DataAnnotations所以另一種選擇是在視圖模型實現IValidatableObject

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
{ 
    if (this.RentDate > this.ReturnDate) 
    { 
     yield return new ValidationResult("Rent date must be prior to return date", new[] { "RentDate" }); 
    } 
} 
3

如果你正在使用.NET Framework 3.0或更高版本,你可以做到這一點作爲一個類擴展...

/// <summary> 
    /// Determines if a <code>DateTime</code> falls before another <code>DateTime</code> (inclusive) 
    /// </summary> 
    /// <param name="dt">The <code>DateTime</code> being tested</param> 
    /// <param name="compare">The <code>DateTime</code> used for the comparison</param> 
    /// <returns><code>bool</code></returns> 
    public static bool isBefore(this DateTime dt, DateTime compare) 
    { 
     return dt.Ticks <= compare.Ticks; 
    } 

    /// <summary> 
    /// Determines if a <code>DateTime</code> falls after another <code>DateTime</code> (inclusive) 
    /// </summary> 
    /// <param name="dt">The <code>DateTime</code> being tested</param> 
    /// <param name="compare">The <code>DateTime</code> used for the comparison</param> 
    /// <returns><code>bool</code></returns> 
    public static bool isAfter(this DateTime dt, DateTime compare) 
    { 
     return dt.Ticks >= compare.Ticks; 
    } 
0

型號:

[DateCorrectRange(ValidateStartDate = true, ErrorMessage = "Start date shouldn't be older than the current date")] 
public DateTime StartDate { get; set; } 

[DateCorrectRange(ValidateEndDate = true, ErrorMessage = "End date can't be younger than start date")] 
public DateTime EndDate { get; set; } 

屬性類:

[AttributeUsage(AttributeTargets.Property)] 
    public class DateCorrectRangeAttribute : ValidationAttribute 
    { 
     public bool ValidateStartDate { get; set; } 
     public bool ValidateEndDate { get; set; } 

     protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
     { 
      var model = validationContext.ObjectInstance as YourModelType; 

      if (model != null) 
      { 
       if (model.StartDate > model.EndDate && ValidateEndDate 
        || model.StartDate > DateTime.Now.Date && ValidateStartDate) 
       { 
        return new ValidationResult(string.Empty); 
       } 
      } 

      return ValidationResult.Success; 
     } 
    } 
相關問題