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

时间:2012-06-23 20:58:56

标签: jquery asp.net-mvc-3 validation unobtrusive-javascript

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

 <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>

1 个答案:

答案 0 :(得分:0)

请改为尝试:

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