使用Bootstrap日期时间选择器,Asp.Net MVC4应用程序中的Jquery验证插件验证日期和日期时间

Tho*_*mas 4 jquery-validate unobtrusive-validation asp.net-mvc-4 eonasdan-datetimepicker

我目前正在使用Bootstrap 3.1.1,Eonasdan日期时间选择器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; }
    
        ...        
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 我的观点看起来像这样:

    <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>
    
    Run Code Online (Sandbox Code Playgroud)
  • 初始化日期时间选择器的关联Js代码:

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

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

    在此输入图像描述

    我知道jQuery.validator使用jquery.ui.datepicker可以正常工作,但是如何使用bootstrap.datetimepicker呢?

Tho*_*mas 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);
Run Code Online (Sandbox Code Playgroud)

因为引导日期时间选择器使用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);
Run Code Online (Sandbox Code Playgroud)