结束日期大于开始日期验证 javascript 无法正常工作

End-date greater than start-date validation javascript not working properly

提问人:jonny 提问时间:6/24/2012 最后编辑:Leniel Maccaferrijonny 更新时间:4/5/2016 访问量:4295

问:

我正在尝试对我的日期进行验证,以便结束日期大于开始日期,但不起作用。我做错了什么?

 <head>
 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
 <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
  <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />       
  <script src="@Url.Content("~/Scripts/jquery-ui-1.8.19.min.js")" type="text/javascript"></script>
  <script src="@Url.Content("~/Scripts/jquery-ui.unobtrusive.min.js")" type="text/javascript"></script>   
  <script src="@Url.Content("~/Scripts/jquery-ui.unobtrusive-0.5.0.min.js")" type="text/javascript"></script>
  <script src="@Url.Content("~/Scripts/gen_validatorv4.js")" type="text/javascript"></script>

  </head>
     @using (Html.BeginForm("SearchFree", "Reservation", FormMethod.Get,new {id = "form" }))
   {                    

  <h7>Introduceti perioada Rezervarii</h7>
<div class="editor-label">
<label id="cautare" for="StartDate">Data Intrare:   </label>@(Html.JQueryUI().Datepicker("StartDate").DateFormat("mm-dd-yy").MinDate(DateTime.Today).ShowButtonPanel(true).ChangeYear(true).ChangeMonth(true).NumberOfMonths(2))
</div>
<div class="editor-label">
<label  id="cautare"  for="EndDate">Data Iesire:</label>@(Html.JQueryUI().Datepicker("EndDate").DateFormat("mm-dd-yy").MinDate(DateTime.Today).ShowButtonPanel(true).ChangeYear(true).ChangeMonth(true).NumberOfMonths(2))

</div>

<p>
    <input id="buton1" type="submit" value="Cauta camere libere" />
</p>

      }
      <script type="text/javascript">
         $(document).ready(function () {
    $.validator.addMethod("EndDate", function (value, element) {
        var startDate = $('.StartDate').val();
        return Date.parse(startDate) <= Date.parse(value);
    }
      , "* End date must be after start date");
     $('.form').validate();
    });
      </script>
jquery asp.net-mvc-3 验证 unobtrusive-javascript

评论

0赞 Leniel Maccaferri 6/24/2012
你得到的错误是什么?
0赞 jonny 6/24/2012
我没有收到任何错误,只是没有进行验证
0赞 Leniel Maccaferri 6/24/2012
试试我发布的代码作为答案,让我知道它是否适合你......您当前的代码可能在某处出现错误。若要查看错误,可以使用 Firebug 调试 jQuery 代码,例如: getfirebug.com

答:

0赞 Leniel Maccaferri 6/24/2012 #1

请尝试以下操作:

jQuery.validator.addMethod("greaterThan", 
function(value, element, params) {

    if (!/Invalid|NaN/.test(new Date(value))) {
        return new Date(value) > new Date($(params).val());
    }

    return isNaN(value) && isNaN($(params).val()) 
        || (Number(value) > Number($(params).val())); 
},'Must be greater than {0}.');

这样使用:

$(".EndDate").rules('add', { greaterThan: ".StartDate" });

$("form").validate({
    rules: {
        EndDate: { greaterThan: ".StartDate" }
    }
});