I'm working on an ASP.NET MVC 5 project. I have two text boxes in a view like so ...
@Html.TextBox("earliestDate", Model.Checklists.EarliestDate)
@Html.TextBox("latestDate", Model.Checklists.LatestDate)
I'm entering the dates "01/03/2014" (1st March 2014) and "31/03/2014" (31st March 2014). When I place a breakpoint in the controller, I can see that in the controller earliestDate has the value "03/01/2014" (the day and month I entered have been swapped around) while latestDate is null. The code works as desired if I enter the dates in yyyy-MM-dd format.
I followed the advice in this article.
I have installed "globalize.js" and added the code from the article to my view. Nothing changed, I still got the results described above. So I tried modifying the code to specify the desired culture explicitly like so, old code commented out, my new code beneath it ...
@*<script src="~/Scripts/globalize/cultures/globalize.culture.@(System.Threading.Thread.CurrentThread.CurrentCulture.Name).js"></script>*@
<script src="~/Scripts/globalize/cultures/globalize.culture.en-IE.js"></script>
and ...
//Globalize.culture('@(System.Threading.Thread.CurrentThread.CurrentCulture.Name)');
Globalize.culture('en-IE');
This still didn't make any difference. So I tried explicitly adding the desired format to the validator.methods.date
function like so ...
$.validator.methods.date = function (value, element) {
return this.optional(element) ||
Globalize.parseDate(value) ||
Globalize.parseDate(value, "dd-MM-yyyy") || // new code
Globalize.parseDate(value, "yyyy-MM-dd");
}
Still no difference. What am I missing?
For reference, here is the complete script section from the view including the above modifications ...
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/globalize/globalize.js"></script>
@*<script src="~/Scripts/globalize/cultures/globalize.culture.@(System.Threading.Thread.CurrentThread.CurrentCulture.Name).js"></script>*@
<script src="~/Scripts/globalize/cultures/globalize.culture.en-IE.js"></script>
<script>
$.validator.methods.number = function (value, element) {
return this.optional(element) ||
!isNaN(Globalize.parseFloat(value));
}
$(document).ready(function () {
//Globalize.culture('@(System.Threading.Thread.CurrentThread.CurrentCulture.Name)');
Globalize.culture('en-IE');
});
</script>
<script>
jQuery.extend(jQuery.validator.methods, {
range: function (value, element, param) {
//Use the Globalization plugin to parse the value
var val = Globalize.parseFloat(value);
return this.optional(element) || (
val >= param[0] && val <= param[1]);
}
});
$.validator.methods.date = function (value, element) {
return this.optional(element) ||
Globalize.parseDate(value) ||
Globalize.parseDate(value, "dd/MM/yyyy") || // new code
Globalize.parseDate(value, "yyyy-MM-dd");
}
</script>
}