2012-12-07 28 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; 
     } 
    } 
相关问题