ASP MVC 5客户端验证日期时间范围

MrS*_*Scf 7 c# asp.net-mvc jquery

我想检查表单中的Datetime字段.该字段在01/10/2008和01/12/2008之间有效.以下是我定义viewmodel属性的方法:

    [Required(ErrorMessage = "The date value is mandatory")]
    [DataType(DataType.DateTime)]
    [Range(typeof(DateTime), "01/10/2008", "01/12/2008")]
    [DisplayName("When the work starts")]
    public DateTime StartWork { get; set; }
Run Code Online (Sandbox Code Playgroud)

我想在客户端验证这一点.但我总是犯错误.我给出了值01/11/2008并告诉我,日期必须在01/10/2008和01/12/2008之间定义.我读到它没有jquery的客户端验证工作,不是吗?或者我忘了什么?有什么替代方案可以解决这个问题.

Sak*_*ket 13

我想你可以在MVC中使用自定义验证来实现这一点.试试这个:

[ValidateDateRange]
public DateTime StartWork { get; set; }
Run Code Online (Sandbox Code Playgroud)

这是您的自定义验证实现:

namespace MVCApplication
    {   

        public class ValidateDateRange: ValidationAttribute
        {
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {                 
               // your validation logic
                if (value >= Convert.ToDateTime("01/10/2008") && value <= Convert.ToDateTime("01/12/2008") )
                {
                    return ValidationResult.Success;
                }
                else
                {
                    return new ValidationResult("Date is not in given range.");
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

更新:

您还可以将日期范围作为参数传递,以使验证成为通用验证:

[ValidateDateRange(FirstDate = Convert.ToDateTime("01/10/2008"), SecondDate = Convert.ToDateTime("01/12/2008"))]
public DateTime StartWork { get; set; }
Run Code Online (Sandbox Code Playgroud)

自定义验证:

    namespace MVCApplication
        {   

            public class ValidateDateRange: ValidationAttribute
            {
              public DateTime FirstDate { get; set; }
              public DateTime SecondDate { get; set; }

                protected override ValidationResult IsValid(object value, ValidationContext validationContext)
                {                 
                    // your validation logic
                    if (value >= FirstDate && value <= SecondDate)
                    {
                        return ValidationResult.Success;
                    }
                    else
                    {
                        return new ValidationResult("Date is not in given range.");
                    }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

更新2 :(对于客户端) 一个非常简单的jQuery逻辑应该进行客户端验证.检查如下:

$(document).ready(function(){

  $("#btnSubmit").click(function(){

    var dt = $("#StartWork").val();

    var d = new Date(dt);
    var firstDate = new Date("2008-01-10");
    var secondDate = new Date("2008-01-12");

    if(d>= firstDate && d<= secondDate)
    {
      alert("Success");
    }
    else
    {
      alert("Date is not in given range.");
    }

  });

});
Run Code Online (Sandbox Code Playgroud)

请检查此JSFiddle以查看工作演示:日期范围验证