客户端验证的原因是jquery.validate.unobtrusive.js 使用的jquery.validate.js 插件基于MM/dd/yyyy 格式验证日期,而您输入的日期基于dd/MM/yyyy 格式。
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.globalize 插件。
您也可以编写自己的脚本。请注意,以下脚本取自我自己的插件,该插件与生成日期选择器的@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] 属性什么都不做,可以删除。