I'm trying to validate an EndDate to be greater than a StartDate using MVC Foolproof Unobtrusive validation.
The problem is that it's using American date format, while my app is supposed to be in European date format. i.e. a period of 03/02 - 02/03 (3 Feb - 2 Mar) is being read as 2 Mar - 3 Feb and thus throwing validation errors.
My model:
[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; }
In the .cshtml:
$('#StartDate, #EndDate').datepicker({
dateFormat: "dd/mm/yy",
defaultDate: $(this).val()
});
-snip-
<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>
I've already done an override on the jQuery validation date parsing as follows, but it seems to have no effect, it's still being compared in American.
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;
}
});
}
});