C#属性用于检查一个日期是否早于另一个日期

时间:2012-12-07 14:07:39

标签: c# asp.net asp.net-mvc-4

我有一个包含两个DateTime属性的MVC4 Prject的ViewModel:

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

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

有一种简单的方法可以使用C#属性作为[Compare("someProperty")]来检查天气,RentDate属性的值是否早于ReturnDate的值?

6 个答案:

答案 0 :(得分:24)

这是一个非常快速的基本实现(没有错误检查等)应该做你要求的(仅在服务器端...它不会做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; }
   }
}

答案 1 :(得分:4)

看起来您正在使用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" });
    }
}

答案 2 :(得分:2)

如果您使用的是.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;
    }

答案 3 :(得分:1)

不确定它在MVC / Razor中使用,但是..

您可以使用DateTime.Compare(t1,t2) - t1和t2是您要比较的次数。它将返回-1,0或1,具体取决于结果。

在这里阅读更多内容: http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx

答案 4 :(得分:0)

框架中没有类似的东西。常见的类似属性是RequiredIf。这篇文章对此进行了描述。

RequiredIf Conditional Validation Attribute

答案 5 :(得分: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;
        }
    }