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

时间:2014-11-28 05:44:50

标签: c# jquery asp.net-mvc

我想检查表单中的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; }

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

5 个答案:

答案 0 :(得分:12)

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

[ValidateDateRange]
public DateTime StartWork { get; set; }

以下是您的自定义验证实现:

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.");
                }
            }
        }
    }

<强>更新

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

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

自定义验证:

    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.");
                    }
                }
            }
        }

更新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.");
    }

  });

});

请检查此JSFiddle以查看工作演示:Date Range Validation

答案 1 :(得分:3)

您必须在属性上以特定格式指定日期,并且您还要提供该格式的值。日期输入不喜欢MM/dd/yyyy,即使这是它显示的格式!相当迟钝的恕我直言。

你需要像这样添加min和max:

生成的HTML

<input class="form-control text-box single-line input-validation-error" data-val="true" data-val-date="The field DOB must be a date." data-val-required="The DOB field is required." id="DOB" name="DOB" type="date" value="1932-01-01" aria-required="true" aria-describedby="DOB-error" aria-invalid="true" min="1932-01-01" max="2015-01-01">

<强>模型

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }

查看

@Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control", min = "1900-01-01", max = "2015-01-01" } })

然后您将在UI中获得最小或最大错误:

enter image description here

答案 2 :(得分:1)

尽管其中的一部分已经过发布,但由于不起作用而被否决。只要您同时指定了范围和格式字符串,我就可以确认它确实有效。

ScrollView:
    size_hint: (None, 1)
    width: grid.width
    pos_hint: {'center_x':0.5}

    GridLayout:
        id: grid
        cols: 1
        padding: 0
        spacing: 0, 0
        size_hint: None, None
        size: self.minimum_size
        BoxLayout:
            orientation: "horizontal"
            size_hint: None, None
            size: self.minimum_size
            spacing: 0
            padding: 0

            CheckBox:
                group: "notIdentReason"
                size_hint: None, None
                size: lab.height, lab.height
            Label:
                id: lab
                text: "Sample rejected"
                font_size: 24
                color: 0, 0, 0, 1
                size_hint: None, None
                size: self.texture_size

        BoxLayout:
            orientation: "horizontal"
            size_hint: None, None
            size: self.minimum_size
            spacing: 0
            padding: 0

            CheckBox:
                group: "notIdentReason"
                size_hint: None, None
                size: lab.height, lab.height
            Label:
                text: "Unsubtyping"
                font_size: 24
                color: 0, 0, 0, 1
                size_hint: None, None
                size: self.texture_size

        BoxLayout:
            orientation: "horizontal"
            size_hint: None, None
            size: self.minimum_size
            spacing: 0
            padding: 0

            CheckBox:
                group: "notIdentReason"
                size_hint: None, None
                size: lab.height, lab.height
            Label:
                text: "Other"
                font_size: 24
                color: 0, 0, 0, 1
                size_hint: None, None
                size: self.texture_size

答案 3 :(得分:0)

检查范围日期也可以使用FluentValidation完成,这可以是您问题的另一种解决方案,请检查我的答案。希望这有帮助

MVC model validation for date

答案 4 :(得分:-3)

使用DataFormat属性明确指定日期格式,

[DisplayFormat(DataFormatString="{0:C}")]

参考MSDN doc