jQuery 如何修复mvc中日期时间属性上的“字段必须是日期”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30510221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:41:51  来源:igfitidea点击:

how to fix 'The field must be a date' on a datetime property in mvc

jqueryasp.net-mvcjquery-uiasp.net-mvc-5

提问by rumi

I need to capture date and time both for my model property. In my model class I have the following

我需要为我的模型属性捕获日期和时间。在我的模型课中,我有以下内容

[Required]
[DataType(DataType.DateTime)]
public DateTime? CallBackDate { get; set; }

When I enter a valid date time (e.g. 28/05/2015 15:55) I keep getting this error The field CallBackDate must be a date.

当我输入有效的日期时间(例如28/05/2015 15:55)时,我不断收到此错误The field CallBackDate must be a date.

I have seen similar question and tried various answers but nothing seems to get rid of this. I m using unobtrusive client side validation and I can't disable it.

我见过类似的问题并尝试了各种答案,但似乎没有什么能摆脱这一点。我正在使用不显眼的客户端验证,我无法禁用它。

The source of the input field has the following markup

输入字段的来源有以下标记

<input autocomplete="off" class="jquery_datetimepicker form-control hasDatepicker" data-val="true" data-val-date="The field CallBackDate must be a date." data-val-required="The CallBackDate field is required." id="CallBackDate" name="CallBackDate" placeholder="Enter your CallBackDate" type="text" value="">

And jquery datetime picker has the following markup

并且 jquery 日期时间选择器具有以下标记

$('.jquery_datetimepicker').datetimepicker({
    dateFormat: 'dd/mm/yy',
    minDate: 0,
    showWeeks: true,
    showStatus: true,
    highlightWeek: true,
    numberOfMonths: 1,
    showAnim: "scale",
    showOptions: {
        origin: ["top", "left"]
    },
    timeFormat: 'hh:mm tt'
});

Any ideas? thanks

有任何想法吗?谢谢

回答by lukyer

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.jswhich does not accept date/datetime format in any way. It is not caused by datepicker nor browsers. Unfortunately you have to solve it manually.

客户端验证问题可能是由于jquery.validate.unobtrusive.min.js 中的 MVC 错误(即使在 MVC 5 中)而发生它不以任何方式接受日期/日期时间格式。它不是由日期选择器或浏览器引起的。不幸的是,您必须手动解决它。

My finally working solution:

我最终的工作解决方案:

You have to include before:

您必须先包括:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:

您可以使用以下方法安装 moment.js:

Install-Package Moment.js

And then you can finally add fix for date format parser:

然后你终于可以为日期格式解析器添加修复:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

回答by IkManu

I added the fix for date format parser, but I needed to set the format to 'L' so it could be work in all Locales:

我添加了日期格式解析器的修复程序,但我需要将格式设置为“L”,以便它可以在所有语言环境中使用:

$(function () {
$.validator.methods.date = function (value, element) {
    return this.optional(element) || moment(value, "L", true).isValid();
}
});

回答by voltdev

In the modelfor example:

例如在模型中:

    [Display(Name = "Insert Start Date")]
    [Required(ErrorMessage = "You must specify the date of the event!")]
    [DataType(DataType.DateTime, ErrorMessage = "Podaj prawid?ow? dat? wydarzenia")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm}", ApplyFormatInEditMode = true)]
    public DateTime StartDate { get; set; }

    [Display(Name = "Insert End Date")]
    [Required(ErrorMessage = "You must specify the date of the event!")]
    [DataType(DataType.DateTime, ErrorMessage = "Podaj prawid?ow? dat? wydarzenia")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm}", ApplyFormatInEditMode = true)]
    public DateTime EndDate { get; set; }

And Viewmy example code:

查看我的示例代码:

<script>
$('#startDate').datetimepicker({
    onClose: function (dateText, inst) {
        var endDateTextBox = $('#endDate');
        if (endDateTextBox.val() != '') {
            var testStartDate = new Date(dateText);
            var testEndDate = new Date(endDateTextBox.val());
            if (testStartDate > testEndDate)
                endDateTextBox.val(dateText);
        }
        else {
            endDateTextBox.val(dateText);
        }
    }, dateFormat: 'yy-mm-dd',
    onSelect: function (selectedDateTime) {
        var start = $(this).datetimepicker('getDate');
        $('#endDate').datetimepicker('option', 'minDate', new Date(start.getTime()));
    }
}); ....

This caused positive effects: dateFormat: 'yy-mm-dd',

这引起了积极的影响: dateFormat: 'yy-mm-dd',

回答by Vaibhav Nagar

$(function () {
    $.validator.addMethod('date',
    function (value, element) {
        if (this.optional(element)) {
            return true;
        }
        var valid = true;
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        }
        catch (err) {
            valid = false;
        }
        return valid;
    });
    $(".datetype").datepicker({ dateFormat: 'dd/mm/yy' });
});

Put this code in a file datepicker.js and include this file in html

将此代码放在文件 datepicker.js 中并将此文件包含在 html 中

回答by kspearrin

You need to make sure your application's Cultureis properly set.

您需要确保正确设置了应用程序的文化

Example

例子

The following example shows how cultures affect date parsing: https://dotnetfiddle.net/vXQTAZ

以下示例显示了文化如何影响日期解析:https: //dotnetfiddle.net/vXQTAZ

DateTime dateValue;
string dateString = "28/05/2015 15:55";

if (DateTime.TryParse(dateString, CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, out dateValue))
{
    Console.WriteLine("Valid en-US date.");
}
else
{
    Console.WriteLine("Not a valid en-US date.");
}

if (DateTime.TryParse(dateString, CultureInfo.CreateSpecificCulture("fr-FR"), DateTimeStyles.None, out dateValue))
{
    Console.WriteLine("Valid fr-FR date.");
}
else
{
    Console.WriteLine("Not a valid fr-FR date.");
}

Output

输出

Not a valid en-US date.

Not a valid en-US date.

Valid fr-FR date.

Valid fr-FR date.

Client Side Settings

客户端设置

You may also need to make sure that your client side validators are using properly cultures/globalization. If you are using jQuery validate plugin with MVC, see this extension to help modify that plugin to meet your needs: http://blog.icanmakethiswork.io/2012/09/globalize-and-jquery-validate.html

您可能还需要确保您的客户端验证器使用正确的文化/全球化。如果您在 MVC 中使用 jQuery 验证插件,请参阅此扩展以帮助修改该插件以满足您的需求:http: //blog.icanmakethiswork.io/2012/09/globalize-and-jquery-validate.html

回答by Kiran Nandan

  1. Add following method in the additional-methods.js file and include this file in your project:
  1. 在 additional-methods.js 文件中添加以下方法并将此文件包含在您的项目中:

      $.validator.addMethod('date',
        function (value, element) {
            if (this.optional(element)) {
                return true;
            }
            var valid = true;
            try {
                $.datepicker.parseDate('dd/mm/yy', value);
            }
            catch (err) {
                valid = false;
            }
            return valid;
        });
      $.validator.addMethod('date',
        function (value, element) {
            if (this.optional(element)) {
                return true;
            }
            var valid = true;
            try {
                $.datepicker.parseDate('dd/mm/yy', value);
            }
            catch (err) {
                valid = false;
            }
            return valid;
        });
  1. View must be like this:
  1. 视图必须是这样的:
       @Html.TextBoxFor(model => model.DOB, new { @class = "datetype", type ="text" })
       @Html.ValidationMessageFor(model => model.DOB)
     $(function () {
              $(".datetype").datepicker({ dateFormat: 'dd/mm/yy' }); 
      });

It works for me.

这个对我有用。

回答by Mustufa

I have to validate dd/mm/yyyy hh:iiand with help of @lukyer answer i have added DD/MM/YYYY HH:mmand it is working fine Hope this help !

我必须验证dd/mm/yyyy hh:ii并在我添加的@lukyer 答案的帮助下 DD/MM/YYYY HH:mm,它工作正常希望这有帮助!

回答by Adleri

I couln't solve it by the others answers. In my case, using TextBoxFor wasn't mandatory; I used TextBox instead.

我无法通过其他人的答案解决它。就我而言,使用 TextBoxFor 不是强制性的;我用 TextBox 代替。

Model

模型

[Required(ErrorMessage = "Required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime MyDate{get;set;}

View

看法

@Html.TextBox("MyDate", DateTime.Now.ToString(), new {@type="datetime"})

回答by Bengü Hasdil

localization or moment.js was not work for me while using datetimepicker. splitting hour and then checking is working. I am using format: 'dd.mm.yyyy hh:ii' for datetimepicker.

使用 datetimepicker 时,本地化或 moment.js 对我不起作用。拆分小时,然后检查工作。我正在使用格式:'dd.mm.yyyy hh:ii' 作为日期时间选择器。

$.validator.methods.date = function (value, element) {
    var dateL = value.split(" ");
    var date = dateL[0].split(".");
    var hour = dateL.length > 1 ? dateL[1].split(":") : "";
    return this.optional(element) || !/Invalid|NaN/.test(dateL.length > 1 ? new Date(date[2], date[1], date[0],hour[0],hour[1]).toString() : new Date(date[2], date[1], date[0]).toString());
}

回答by Musa Aliji

if you use JQuery unubtrosive validation you can add rules like behind and to change client-side validation message.

如果您使用 JQuery unubtrosive 验证,您可以添加规则,如背后和更改客户端验证消息。

$('#inputName').rules('add',{
   messages:{
       date:'Invalid format date'
   }
})