13

我的 MVC4 项目有一个 ViewModel,其中包含两个 DateTime 属性:

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

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

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

4

6 回答 6

27

这是一个非常快速的基本实现(没有错误检查等),应该按照您的要求进行(仅在服务器端......它不会进行 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; }
   }
}
于 2012-12-07T14:54:08.403 回答
6

看起来您正在使用 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" });
    }
}
于 2012-12-07T14:38:35.167 回答
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;
    }
于 2012-12-07T15:07:32.453 回答
1

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

您可以使用 DateTime.Compare(t1, t2) - t1 和 t2 是您要比较的时间。它将根据结果返回 -1、0 或 1。

在此处阅读更多信息:http: //msdn.microsoft.com/en-us/library/system.datetime.compare.aspx

于 2012-12-07T14:09:51.787 回答
1

模型:

[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;
        }
    }
于 2017-10-10T10:24:59.627 回答
0

框架中不存在类似的东西。一个常见的类似属性是RequiredIf. 在这篇文章中有描述。

RequiredIf 条件验证属性

于 2012-12-07T14:10:50.050 回答