asp.net mvc3模型中的日期比较

Sma*_*boy 0 asp.net-mvc jquery-validate razor asp.net-mvc-3

我的模型中有两个字段

  1. CreateDateTo
  2. CreateDateFrom

这就是这样的

<b>Start Date</b>  @Html.EditorFor(model => model.AdvanceSearch.CreateDatefrom, new {  @class = "picker startDate" })

<b>End Date</b> @Html.EditorFor(model => model.AdvanceSearch.CreateDateto, new { @class = "picker endDate" })
Run Code Online (Sandbox Code Playgroud)

我有一个验证方案,enddate不应该大于开始日期,目前我正在通过jquery验证它

$.validator.addMethod("endDate", function (value, element) {
        var startDate = $('.startDate').val();
        return Date.parse(startDate) <= Date.parse(value);
    }, "* End date must be Equal/After start date");
Run Code Online (Sandbox Code Playgroud)

我想知道在MVC3模型验证中有什么方法可以做到这一点吗?

Nic*_*ick 6

我会说你不应该只依赖Javascript,除非你在某种内联网应用程序中控制你的客户端的浏览器.如果应用程序面向公众 - 请确保您同时拥有客户端和服务器端验证.

此外,可以使用下面显示的自定义验证属性在模型对象中实现服务器端验证的更简洁方法.然后,您的验证将变为集中,您无需明确比较控制器中的日期.

public class MustBeGreaterThanAttribute : ValidationAttribute
{
    private readonly string _otherProperty;

    public MustBeGreaterThanAttribute(string otherProperty, string errorMessage) : base(errorMessage)
    {
        _otherProperty = otherProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(_otherProperty);
        var otherValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
        var thisDateValue = Convert.ToDateTime(value);
        var otherDateValue = Convert.ToDateTime(otherValue);

        if (thisDateValue > otherDateValue)
        {
            return ValidationResult.Success;
        }

        return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后可以将其应用于您的模型,如下所示:

public class MyViewModel
{
    [MustBeGreaterThan("End", "Start date must be greater than End date")]
    public DateTime Start { get; set; }

    public DateTime End { get; set; }

    // more properties...
}
Run Code Online (Sandbox Code Playgroud)