日期验证MVC出错

时间:2015-06-02 10:57:54

标签: asp.net-mvc validation

我的模型类属性看起来像这样

   public DateTime PurchaseDate { get; set; }

和内部视图

 @Html.TextBoxFor(model => model.PurchaseDate, new { @class = "form-control date-picker" })
 @Html.ValidationMessageFor(model => model.PurchaseDate)

我正在以表格

给出这样的日期
19/06/2015

但它提供了验证消息,不允许提交页面,消息就像这样

The field PurchaseDate must be a date.

如果我以mm/dd/yyyy格式提供日期,则可以。谁能指出我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

如果要显式设置模型属性的预期日期格式,则可以使用DisplayAttribute

执行此操作
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime PurchaseDate { get; set; }

否则,将使用服务器的当前文化(在您的情况下恰好是MM/dd/yyyy)。

为了让客户端验证尊重DataFormatString,我们需要使用EditorFor代替TextBoxFor

 @Html.EditorFor(model => model.PurchaseDate, new { @class = "form-control date-picker" })
 @Html.ValidationMessageFor(model => model.PurchaseDate)

答案 1 :(得分:2)

发生客户端错误,因为默认情况下jquery.validate使用MM/dd/yyyy格式测试值。您可以覆盖$.validator.addMethod('date', function (value, element)函数以测试该值是否在您期望的dd/MM/yyyy中。请注意,以下代码来自我自己的jquery插件,该插件与@Html.DatePickerFor()辅助方法相关联,该方法根据服务器文化在输出中呈现data-dateformat属性,因此可能对您的需求而言过度杀伤

添加以下脚本(document.ready中的不是,但在jquery.validate.unobtrusive之后)

Date.prototype.isValid = function () {
  return !isNaN(this.getTime());
}

globalDate = function (value, formatString) {
  // 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]+)/);
  //var format = regex.exec(this.inputFormat);
  var format = regex.exec(formatString);
  // 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;
}

$.validator.addMethod('date', function (value, element) { 
  var format = "dd/MM/yyyy";
  return this.optional(element) || globalDate(value, format).isValid();
}

如果您只想测试格式dd/MM/yyyy,那么只需使用

即可简化globalDate()功能
var date = new Date();
date.setHours(0, 0, 0, 0);
var components = value.split('/');
var day = components[0];
var month = components[1];
var year = components[2];
date.setFullYear(year);
....

修改

除了OP关于服务器端验证失败的评论之外,服务器文化还需要接受dd/MM/yyyy格式的日期字符串。在web.config.cs文件

<system.web>
  <globalization culture="en-AU" uiCulture="en-AU"/> // adjust to your culture code
  ....