客户端验证的原因是jquery.validate.js
使用的插件jquery.validate.unobtrusive.js
验证日期基于MM/dd/yyyy
格式和您输入的日期基于dd/MM/yyyy
format.
具体使用的代码在jquery.validate.js
用于验证的是
date: function(value, element) {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}
根据您使用的浏览器会产生不同的结果(在 Chrome 中,new Date('22/12/1986')
回报Invalid Date
但在 FireFox 中它返回1987-10-11T13:30:00.000Z
这是有效的,只是不是您输入的日期)
您需要覆盖$.validator
以您的文化格式化日期。一种选择是使用jquery.全球化 plugin.
或者,您可以编写自己的脚本。请注意,以下脚本取自我自己的插件,与@Html.DatePickerFor()
生成日期选择器的扩展方法。扩展方法根据服务器区域性为日期格式添加 html 属性,并使用var format = regex.exec(this.inputFormat);
我已注释掉并替换为您的硬编码格式的代码行。如果你只想dd/MM/yyyy
格式,那么脚本可以简化,因为你只需要 'little-endian' 格式
<script type="text/javascript">
// Override default date validator format to allow culture specific format
$.validator.methods.date = function (value, element) {
return this.optional(element) || globalDate(value).isValid();
};
globalDate = function (value) {
// Initialise a new date
var date = new Date(0);
if (value == undefined) {
// Return todays date
return date;
}
// Get the components of the format
// The separator can be forward slash, hyphen, dot and/or space
var regex = new RegExp(/([dMy]+)([\s/.-]+)([dMy]+)([\s/.-]+)([dMy]+)/);
//------------- see notes above
//var format = regex.exec(this.inputFormat);
var format = regex.exec('dd/MM/yyyy');
//-------------
// Get the components of the value
regex = new RegExp(/(\d+)([\s/.-]+)(\d+)([\s/.-]+)(\d+)/);
value = regex.exec(value);
// Check the value is valid
if (value === null || value[2] !== format[2] || value[4] !== format[4]) {
// Its not valid
date.setTime(Number.NaN);
return date;
}
// TODO: What if year entered as 2 digits?
var day = Number.NaN;
var month = Number.NaN;
var year = Number.NAN;
if (format[1].charAt(0) === 'd') {
// little-endian (day, month, year)
day = parseInt(value[1]);
month = parseInt(value[3]) - 1;
year = parseInt(value[5]);
} else if (format[1].charAt(0) === 'M') {
// middle-endian (month, day, year)
day = parseInt(value[3]);
month = parseInt(value[1]) - 1;
year = parseInt(value[5]);
} else {
// big endian (year, month, day)
day = parseInt(value[5]);
month = parseInt(value[3]) - 1;
year = parseInt(value[1]);
}
date.setFullYear(year);
date.setMonth(month);
date.setDate(day);
// Check its valid
if (date.getDate() !== day || date.getMonth() !== month || date.getFullYear() !== year) {
date.setTime(Number.NaN);
return date;
}
return date;
}
// Methods
Date.prototype.isValid = function () {
return !isNaN(this.getTime());
}
</script>
旁注:你的[RegularExpression]
属性不执行任何操作并且可以删除。