C# 该字段必须是日期 - Chrome 中的 DatePicker 验证失败 - mvc

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16284385/
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-10 00:38:24  来源:igfitidea点击:

The field must be a date - DatePicker validation fails in Chrome - mvc

c#jqueryasp.net-mvcgoogle-chromedatepicker

提问by Cristiano

I have strange problem. My date validation doesn't work in Chrome. I've tried thisanswer but it didn't work for me.

我有奇怪的问题。我的日期验证在 Chrome 中不起作用。我试过这个答案,但它对我不起作用。

I have this in my model:

我的模型中有这个:

[Display(Name = "Date")]
[DataType(DataType.Date)]
public DateTime Date { get; set; }

My View:

我的看法:

<div class="editor-field">
@Html.TextBoxFor(model => model.Item.Date, new { @class = "picker" })
@Html.ValidationMessageFor(model => model.Item.Date)
</div>

$(document).ready(function () {
    $('.picker').datepicker({
        dateFormat: 'dd.mm.yy',
        changeMonth: true,
        changeYear: true,
        selectOtherMonths: true
    });
});

Everything works in Opera and Firefox but Chrome doesn't like this type of date. I'm constantly getting the following error The field 'Date' must be a date.

在 Opera 和 Firefox 中一切正常,但 Chrome 不喜欢这种类型的日期。我不断收到以下错误The field 'Date' must be a date

Any ideas?

有任何想法吗?

UPDATE

更新

It seems there is a problem when the code is inside a partial view. When I copy that code to a main page, validation works fine.

当代码位于局部视图中时,似乎存在问题。当我将该代码复制到主页时,验证工作正常。

I'm inserting partial view inside my main View simply like this:

我在我的主视图中插入部分视图,就像这样:

@Html.Partial("_CreateOrEdit", Model)

And that code above is inside a partial view:

上面的代码在局部视图中:

@model Pro.Web.Models.Model

<div class="editor-field">
@Html.TextBoxFor(model => model.Item.Date, new { @class = "picker" })
@Html.ValidationMessageFor(model => model.Item.Date)

$(document).ready(function () {
$('.picker').datepicker({
    dateFormat: 'dd.mm.yy',
    changeMonth: true,
    changeYear: true,
    selectOtherMonths: true
});

</script>
});

UPDATE2

更新2

It doesn't work after all. Sometimes it works, sometimes not. I clicked a couple of times on dates and sometimes validation passes. For the same date there could be good and wrong validation.

毕竟它不起作用。有时有效,有时无效。我在日期上单击了几次,有时还通过了验证。对于同一日期,可能存在好的和错误的验证。

This is output html for date field:

这是日期字段的输出 html:

<div class="editor-field">
<input class="picker" data-val="true" data-val-date="The field Date must be a date." data-val-required="The Date field is required." id="date" name="Item.Date" type="text" value="1.1.0001. 0:00:00" />
<span class="field-validation-valid" data-valmsg-for="Item.Date" data-valmsg-replace="true"></span>
</div>

回答by Piotr Stapp

In my opinion problems is that MVC is generating for date HTML5 input with [type=date]. This causes that in chrome valid date format is same same as system date format.

在我看来,问题在于 MVC 正在为日期 HTML5 输入生成[type=date]. 这导致 Chrome 中的有效日期格式与系统日期格式相同。

You can probably set date format in MVC to be common with JqueryUI using following attribute:

您可以使用以下属性将 MVC 中的日期格式设置为与 JqueryUI 通用:

[DataType(DataType.Date), DisplayFormat( DataFormatString="{0:dd.MM.yy}", ApplyFormatInEditMode=true )]

The second idea is to use code from article: Creating a Native HTML 5 Datepicker with a Fallback to jQuery UI

第二个想法是使用文章中的代码:Creating a Native HTML 5 Datepicker with a Fallback to jQuery UI

One more thing. There is a good topic about date in html input: Is there any way to change input type="date" format?

还有一件事。在 html 输入中有一个关于日期的好话题:Is there any way to change input type="date" format?

回答by Hubo

The problem seems to be with <input type="date" />(HTML5) as specificationsays that valid value is defined as RFC3339.

问题似乎出在<input type="date" />(HTML5) 上,因为规范说有效值被定义为RFC3339

So I changed my View to something like this:

所以我把我的观点改成了这样:

<script>
    $(function () {
         $("#validfrom").datepicker({
             altField: "#ValidFrom",
             altFormat: "yy-mm-dd"
         });
    });
</script>

<div class="editor-label">
    @Html.LabelFor(model => model.ValidFrom)
</div>
<div class="editor-field">
    <input id="validfrom" type="text" name="validfrom" />
    @Html.HiddenFor(model => model.ValidFrom)
    @Html.ValidationMessageFor(model => model.ValidFrom)
</div>

Hope it helps.

希望能帮助到你。

回答by user3096151

Exact the same situation here (partial view)

这里的情况完全相同(部分视图)

I solved it by removing the validation attribute and perform validation at server side:

我通过删除验证属性并在服务器端执行验证来解决它:

$('#date').removeAttr("data-val-date");

回答by chassis

It is kind of late to crash to the party after a year, but I've tried every solution I could find regarding this error, and none of them helped. So for anyone struggling like myself here is what solved this issue.

一年后参加聚会有点晚了,但我已经尝试了我能找到的关于这个错误的所有解决方案,但没有一个有帮助。因此,对于像我一样在这里挣扎的人来说,解决了这个问题的方法。

Add to the end of jquery.validate.globalize.js and its minified version(depends on what you are using) this little snippet of code.

添加到 jquery.validate.globalize.js 及其缩小版本的末尾(取决于您使用的是什么)这个小代码片段。

... 
   $.validator.methods.range = function (value, element, param) {
        var val = Globalize.parseFloat(value);
        return originalMethods.range.call(this, val, element, param);
    };


}(jQuery, Globalize));

Globalize.culture("en-GB");

Globalize.culture("en-GB");

Of course, use your own culture settings inside quotation marks.

当然,在引号内使用您自己的文化设置。

Hope it helps!

希望能帮助到你!

回答by István

I solved it by removing the validation attribute

我通过删除验证属性解决了它

@model Pro.Web.Models.Model

<div class="editor-field">
@{ Html.EnableClientValidation(false); }
@Html.TextBoxFor(model => model.Item.Date, new { @class = "picker" })
@Html.ValidationMessageFor(model => model.Item.Date)
@{ Html.EnableClientValidation(true); }

回答by hispeed

I had the same error. Solved it by applying datetime as the type,

我有同样的错误。通过应用日期时间作为类型来解决它,

 @Html.EditorFor(model => model.LineResetAllowStartDate, new { htmlAttributes = new { @class = "form-control" ,  @type = "datetime" } })

similarly use time for only time

同样使用时间作为唯一的时间

 @Html.EditorFor(model => model.LineResetAllowStartDate, new { htmlAttributes = new { @class = "form-control" ,  @type = "time" } })