4

我目前正在使用Bootstrap 3.1.1Eonasdan 日期时间选择器 v4.7.14jquery 验证插件 v1.14.0开发 MVC Asp.Net 4.6 WebApp 。

我在验证日期时遇到了一些问题。

  • 我的模型看起来像这样:

    public class PersonModel{
        ...
    
        [Required]
        [Display(Name = "Date of Birth")]
        public DateTime? DateOfBirth { get; set; }
    
        ...        
    }
    
  • 我的视图看起来像这样:

    <div class="form-group">
        @Html.LabelFor(x => x.DateOfBirth):
        <span class="text-danger"><b>*</b></span>
        <div class="input-group datepicker">
            <span class="input-group-addon">
                <span class="glyphicon glyphicon-calendar"></span>
            </span>
            @Html.TextBoxFor(x => x.DateOfBirth, new {@class = "form-control", @data_date_format = "DD/MM/YYYY", @placeholder = "DD/MM/YYYY"})
        </div>
        @Html.ValidationMessageFor(x => x.DateOfBirth, "", new { @class = "text-danger" })
    </div>
    
  • 用于初始化日期时间选择器的相关 Js 代码:

    (function () {
        // Init bootstrap date/time pickers
        $(".datepicker").datetimepicker({
            useCurrent: false
        });
    })(jQuery);
    

    使用jQuery.validator,即使日期看起来不错,我总是会收到此错误:

    在此处输入图像描述

    我知道jQuery.validatorjquery.ui.datepicker 可以正常工作,但我怎样才能使它与 bootstrap.datetimepicker 一起工作?

4

1 回答 1

8

您可以覆盖插件的date方法:Jquery.validator

(function () {
    // overrides the jquery date validator method
    jQuery.validator.methods.date = function (value, element) {
        // All dates are valid....
        return true;
    };
})(jQuery);

因为引导日期时间选择器使用moment.js,您可以像这样检查日期是否有效:

(function () {
    // overrides the jquery date validator method
    jQuery.validator.methods.date = function (value, element) {
        // We want to validate date and datetime
        var formats = ["DD/MM/YYYY", "DD/MM/YYYY HH:mm"];
        // Validate the date and return
        return moment(value, formats, true).isValid();
    };
})(jQuery, moment);
于 2016-04-28T22:21:02.290 回答