jquery ui datepicker 和 mvc 视图模型类型日期时间

问题描述:

我在我的视图模型上使用 jquery datepicker

I am using jquery datepicker on my view model

这是我的观点:

@Html.TextBoxFor(o => o.JobStartDate, new { id = "dt1", @class = "input-block-level" })
@Html.ValidationMessage("JobStartDate")

和我的脚本:

$("#dt1").datepicker({ dateFormat: "dd/mm/yy" });

如果我的日期

Everything works fine if my date is <= 12, if my date is over 12, it will show me an validation error message saying "The field Start Date must be a date." (I am using jquery validation)

例如:日期 16/12/2014 会给我错误,而 12/12/2014 不会

For example: date 16/12/2014 will give me the error while 12/12/2014 won't

这是我的视图模型:

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

我怀疑我的视图模型预期格式为 mm/dd/yyyy 的日期,而在我的日期选择器上我指定了 dd/mm/yy,有没有办法告诉我的视图模型我期待 dd/mm/yy 格式,以便在日期 >= 12 时不会抛出错误消息.

I am suspecting that my view model is anticipating a date in the format mm/dd/yyyy while on my datepicker i specified dd/mm/yy, is there a way to tell my viewmodel that I am expecting dd/mm/yy format so that it doesn't throw an error message if date is >= 12.

你可以看看使用 jquery globalize 或者添加遵循您的脚本(当然假设服务器文化日期格式是dd/MM/yyy")

You can look at using the jquery globalize or add the following to your script (assuming of course that the server culture date format is 'dd/MM/yyy')

$.validator.addMethod('date', function (value, element) {
  if (this.optional(element)) {
    return true;
  }
  var valid = true;
  try {
    $.datepicker.parseDate('dd/mm/yy', value);
  }
  catch (err) {
    valid = false;
  }
  return valid;
});
$('#dt1').datepicker({ dateFormat: 'dd/mm/yy' });

并且请使用 @Html.ValidationMessageFor(m => m.JobStartDate)