我正在尝试使用 MVC Foolproof Unobtrusive 验证来验证 EndDate 是否大于 StartDate。
问题是它使用美国日期格式,而我的应用程序应该是欧洲日期格式。即 03/02 - 02/03(2 月 3 日 - 3 月 2 日)期间被读取为 3 月 2 日 - 2 月 3 日,因此会引发验证错误。
我的模型:
[Required("StartDate")]
[LessThanOrEqualTo("EndDate", ErrorMessageResourceName = "StartDateLessThanEndDate", ErrorMessageResourceType = typeof(Resources.Resources))]
[System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Date)]
[System.ComponentModel.DataAnnotations.DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[Required("EndDate")]
[GreaterThanOrEqualTo("StartDate", ErrorMessageResourceName = "EndDateGreaterThanStartDate", ErrorMessageResourceType = typeof(Resources.Resources))]
[System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Date)]
[System.ComponentModel.DataAnnotations.DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime EndDate { get; set; }
在 .cshtml 中:
$('#StartDate, #EndDate').datepicker({
dateFormat: "dd/mm/yy",
defaultDate: $(this).val()
});
-剪辑-
<div class="row">
<label class="col-xs-6">@Resources.StartDate</label>
<div class="col-xs-6">
@Html.TextBoxFor(x => x.StartDate, "{0:dd/MM/yyyy}", new { @class = "form-control" })
@Html.ValidationMessageFor(a => a.StartDate)
</div>
</div>
我已经对jQuery验证日期解析做了一个覆盖,如下所示,但它似乎没有效果,它仍然在美国进行比较。
jQuery(function ($) {
if ($.validator != null) {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
try {
$.datepicker.parseDate('dd/mm/yy', value);
return true;
}
catch (err) {
return false;
}
});
}
});