jQuery 字段日期必须是 chrome 中 mvc 中的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15706455/
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
The field date must be a date in mvc in chrome
提问by Karthik Chintala
I'm doing a simple MVC4 Internet application, which allows to add some items to the categories.
我正在做一个简单的 MVC4 Internet 应用程序,它允许向类别添加一些项目。
Here is what i've done so far.
这是我到目前为止所做的。
I've a datepicker in mvc view. The script for the datepicker is like this.
我在 mvc 视图中有一个日期选择器。日期选择器的脚本是这样的。
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$('#dtItemDueDate').datepicker({
dateFormat: 'dd/mm/yy',
minDate: 0
});
});
</script>
My model property :
我的模型属性:
[DisplayName("Item DueDate")]
[Required]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]
[DataType(DataType.DateTime)]
public DateTime? dtItemDueDate { get; set; }
public char charCompleted { get; set; }
and in my view i've done this:
在我看来,我已经做到了:
@Html.TextBoxFor(m => m.dtItemDueDate)
@Html.ValidationMessageFor(m => m.dtItemDueDate)
The error is like this:
错误是这样的:
The field Item DueDate must be a date.
The strange this is that it does work in IE and mozilla, but doesnot work in Chrome.
奇怪的是,它在 IE 和 mozilla 中有效,但在 Chrome 中无效。
I found many posts on SO, but none of them help
我在 SO 上找到了很多帖子,但没有一个有帮助
Any ideas/suggestions ?
任何想法/建议?
回答by Mahesh
Without changing jquery.validate.js, you can use the code snip below in $(document).ready()
:
在不更改 jquery.validate.js 的情况下,您可以使用以下代码片段$(document).ready()
:
jQuery.validator.methods.date = function (value, element) {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (isChrome) {
var d = new Date();
return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
} else {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}
};
回答by Rowan Freeman
Editor note: This answer is no longer valid, as of jQuery 1.9 (2013) the $.browser
method has been removed
编者注:此答案不再有效,从 jQuery 1.9 (2013) 开始,该$.browser
方法已被删除
According to this postit's a known quirk with Webkit-based browsers.
根据这篇文章,这是基于 Webkit 的浏览器的一个已知怪癖。
One solution is to modify jquery.validate.js
by finding the function date: function (value, element)
and put this code in it:
一种解决方案是jquery.validate.js
通过查找函数date: function (value, element)
并将此代码放入其中进行修改:
if ($.browser.webkit) {
//ES - Chrome does not use the locale when new Date objects instantiated:
var d = new Date();
return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
}
else {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}
回答by Chtiwi Malek
Rowan Freeman solution wont work for me since .toLocaleDateString(value)
doesn't parse value
strings
Rowan Freeman 解决方案对我不起作用,因为.toLocaleDateString(value)
它不解析value
字符串
here's the solution i came up with => in jquery.validate.js find this function definition: "date: function (value, element)" and replace the code with:
这是我想出的解决方案 => 在 jquery.validate.js 中找到这个函数定义:“日期:函数(值,元素)”并将代码替换为:
// http://docs.jquery.com/Plugins/Validation/Methods/date
date: function (value, element) {
var d = value.split("/");
return this.optional(element) || !/Invalid|NaN/.test(new Date((/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) ? d[1] + "/" + d[0] + "/" + d[2] : value));
},
回答by KSK
Below is the working code that may helpful for some one to fix the date picker issue in chrome and safari: Model:
以下是可能有助于修复 chrome 和 safari 中的日期选择器问题的工作代码:模型:
public DateTime? StartDate { get; set; }
View:
看法:
@Html.TextBoxFor(model => model.StartDate, "{0:dd/MM/yyyy}", new { @type = "text", @class = "fromDate" })
js:
js:
$(function () {
checkSupportForInputTypeDate();
$('#StartDate').datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});
//Function to configure date format as the native date type from chrome and safari browsers is clashed with jQuery ui date picker.
function checkSupportForInputTypeDate() {
jQuery.validator.methods.date = function (value, element) {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
if (isSafari || isChrome) {
var d = new Date();
return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
} else {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}
};
}
回答by KyleMit
Here's Maxim Gershkovich's solutionspelled out a little more:
以下是马克西姆·格什科维奇( Maxim Gershkovich) 的解决方案,详细说明了一点:
jQuery.validator.methods.date = function (value, element) {
if (value) {
try {
$.datepicker.parseDate('dd/mm/yy', value);
} catch (ex) {
return false;
}
}
return true;
};
Notes:
注意事项:
- This depends on the jQuery datepickermethod that comes with jQuery UI
This is actually more robust that the native date validation that comes with jQueryValidate.
According to the docs on date validation:
Returns true if the value is a valid date. Uses JavaScript's built-in Date to test if the date is valid, and therefore does no sanity checks. Only the format must be valid, not the actual date, eg 30/30/2008 is a valid date.
Whereas
parseDate
will check that the date is valid and actually exists.
- 这取决于jQuery UI 附带的jQuery datepicker方法
这实际上比 jQueryValidate 附带的本机日期验证更健壮。
根据日期验证的文档:
如果值为有效日期,则返回 true。使用 JavaScript 的内置 Date 来测试日期是否有效,因此不进行完整性检查。只有格式必须有效,而不是实际日期,例如 30/30/2008 是有效日期。
而
parseDate
将检查日期是否有效且实际存在。
回答by alansiqueira27
I solved this issue by changing from DateTimeto String.
我通过从DateTime更改为String解决了这个问题。
This is the best solution for a good maintance that I can think at the moment.
这是我目前能想到的良好维护的最佳解决方案。