简体   繁体   English

jQuery datepicker中的日期模型

[英]Date model in jQuery datepicker

I need to store in th SQL-Server DB a date format "29-12-2014" using datepicker but I get the message The field XXX must be a date. 我需要使用datepicker在SQL-Server DB中存储日期格式“29-12-2014”,但我收到消息字段XXX必须是日期。

My last try was Regular Expression: 我的最后一次尝试是正则表达:

Model #1: 型号#1:

[RegularExpression(@"([3][0,1]|[0-2]\d)-([1][0-2]|[0]\d)-(\d\d\d\d)", ErrorMessage = "Valor inválido.")]
public Nullable<DateTime> ETD { get; set; }

Model #2: 型号#2:

[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
public Nullable<DateTime> ETD { get; set; }

View: 视图:

<div class="editor-field">
    @Html.TextBoxFor(model => model.ETD)
    @Html.ValidationMessageFor(model => model.ETD)
</div>

jQuery: jQuery的:

$(function () {
     $("#ETD").datepicker();
});

I always get the message "The field ETD must be a date." 我总是收到消息“字段ETD必须是约会”。

Any idea? 任何的想法?

Thanks. 谢谢。

Its my understanding that the format 'dd-MM-yyyy' is the problem, here. 据我所知,格式'dd-MM-yyyy'就是问题所在。 The jquery unobtrusive validation is trying to instantiate a new Date(strVal) object, and it doesn't know what to do with the string '29-12-2014'. jquery不显眼的验证试图实例化一个新的Date(strVal)对象,它不知道如何处理字符串'29 -12-2014'。

See Unobtrusive validation in Chrome won't validate with dd/mm/yyyy 请参阅Chrome中的不显眼验证,不会使用dd / mm / yyyy进行验证

magritte answered that redefining the unobtrusive validator's date method, using the jQuery Globalize library, to parse with the desired format string should solve the issue: magritte回答说,使用jQuery Globalize库重新定义不显眼的验证器的日期方法,用所需的格式字符串进行解析应解决问题:

$.validator.methods.date = function (value, element) {
    return this.optional(element) || Globalize.parseDate(value, "dd-MM-yyyy", "en");
}

Update 更新

I recreated your problem locally, and was able to replicate the 'required field validation not firing prior to form post' issue, when the Globalization library was not installed. 我在本地重新创建了您的问题,并且能够在未安装Globalization库时复制“在表单发布之前未触发的必需字段验证”。 Once I installed and loaded the library, the front-end worked as expected, with unobtrusive validation accepting the modified dd-MM-yyyy date. 安装并加载库后,前端按预期工作,不显眼的验证接受修改后的dd-MM-yyyy日期。

The library can be installed using the NuGet package manager and the following package: http://www.nuget.org/packages/jquery-globalize/ . 可以使用NuGet包管理器和以下包安装该库: http//www.nuget.org/packages/jquery-globalize/ Then you need to update your html to include the globalize.js script. 然后,您需要更新您的html以包含globalize.js脚本。

The back-end was another story, which is going to rely on your local machine's globalization profile. 后端是另一个故事,它将依赖于您本地机器的全球化配置文件。 I am assuming you are running a non-en/us machine where this format might parse? 我假设您运行的是非en / us机器,此格式可能会解析? My machine is english/us and does not natively parse the modified date format, however using the below command, I successfully got a valid datetime: 我的机器是英语/我们并没有原生解析修改后的日期格式,但是使用下面的命令,我成功获得了一个有效的日期时间:

DateTime.ParseExact(Request.Form["ETD"], "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);

This should work to set your format in the box: 这应该可以在框中设置您的格式:

$("#ETD").datepicker({
    dateFormat    : 'dd-mm-yy'
});

Is the validation message coming from jQuery or C#? 验证消息是来自jQuery还是C#? See this answer with respect to the former: https://stackoverflow.com/a/19519745/1803682 请参阅前者的答案: https//stackoverflow.com/a/19519745/1803682

With the help of @DanS I was able to elaborate a solution for the Date Validation for my country, Portugal (pt-PT) and here is the complete solution for anybody that have a problem validating a date: 在@DanS的帮助下,我能够为我的国家葡萄牙(pt-PT)制定日期验证的解决方案,对于任何验证日期有问题的人来说,这是完整的解决方案:

First of all, you need to install the nuget package: 首先,您需要安装nuget包:

http://www.nuget.org/packages/jquery-globalize/ http://www.nuget.org/packages/jquery-globalize/

Then include in the page where you want to make the validation (or in the Bundle like me) the links to the core library and your country's culture file (note:put always first the core and then the culture file or else you will get an undefined error) 然后在您要进行验证的页面中(或像我这样的Bundle中)包含指向核心库和您所在国家/地区的文化文件的链接(注意:首先放置核心,然后是文化文件,否则您将得到一个未定义的错误)

bundles.Add(new ScriptBundle("~/bundles/saida").Include(
            "~/Scripts/Presenter/Saida/create.js",
            "~/Scripts/Globalize/globalize.js",
            "~/Scripts/Globalize/Cultures/globalize.culture.pt-PT.js",
            "~/Scripts/Common/date.js"));

Set the Model: 设置模型:

[Required(ErrorMessage = "Preenchimento obrigatório.")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
[Display(Name = "Data da DAU")]
public DateTime? DAUData { get; set; }

I did not put any ErrorMessage in the DataType property because it's not passed to the View, instead, you can put a custom message in the View: 我没有在DataType属性中放置任何ErrorMessage,因为它没有传递给View,而是可以在View中放置自定义消息:

<div class="editor-field">
    @Html.EditorFor(model => model.DAUData)
    @Html.ValidationMessageFor(model => model.DAUData, "Formato de data inválido.")
</div>

But if you use the jQuery datepicker function with the definition of the format, you don't need to worry about the format: 但是如果你使用jQuery datepicker函数和格式的定义,你不必担心格式:

$(function ()
{
    $(".datefield").datepicker({ dateFormat: 'dd-mm-yy', changeYear: true });
});

The property changeYear is to presente a dropdown to choose the year (not mandatory, only a nice option to garanty that the value is always valid), and don't forget to inlcude the jQuery and jQueryUI references in your file to presente the calendar correctly. 属性changeYear是提交一个下拉列表来选择年份(不是强制性的,只是保证值始终有效的一个很好的选项),并且不要忘记在文件中包含jQuery和jQueryUI引用以正确地呈现日历。

To complete the client side script, I have the culture's format validation: 要完成客户端脚本,我有文化的格式验证:

$.validator.methods.date = function (value, element)
{
    return this.optional(element) || Globalize.parseDate(value, "dd-MM-yyyy", "pt-PT");
 }

I also have a template for the date format in the View (place it in the Shared/EditorTemplates/ folder and don't forget to user the @Html.EditorFor razor method in the View: 我还在View中有一个日期格式的模板(将它放在Shared / EditorTemplates /文件夹中,不要忘记在View中使用@ Html.EditorFor razor方法:

@{
    var value = "";

    if (Model.HasValue) 
    {
        value = String.Format("{0:d}", Model.Value.ToString("dd-MM-yyyy"));
    }
}

@Html.TextBox("", value, new { @class = "datefield", type = "text", autocomplete = "off"     })

Now anytime that you will need a date, use the Template, and the class "datepicker", and that's it! 现在,只要你需要一个日期,就可以使用模板和类“datepicker”,就是这样!

Thanks again DanS ;) 再次感谢DanS;)

Have you seen this link? 你看过这个链接了吗? I believe they had a similar problem: The field date must be a date in mvc in chrome 我相信他们有类似的问题: 字段日期必须是以mvc为单位的日期

and also this one: Jquery Datepicker Chrome 还有这个: Jquery Datepicker Chrome

The are several things going on in localizing your app. 本地化您的应用程序有几个方面。

This Phil Haack article goes through it. 菲尔哈克的这篇文章经历过这篇文章 It's pretty old, but I guess all the concepts are the same. 它已经很老了,但我想所有的概念都是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM