4

I'm having problem with date validation. In my View, I have a jQuery datepicker - I changed the format from yy/mm/dd to mm/dd/yy and now I get client-side validation errors. For example,

    The value '02/25/2014' is not valid for Date of Birth.

The Javascript:

$('#DateOfBirth').datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: "mm/dd/yy",
    yearRange: "-90:-5"
});

The View Model:

    [Required]
    [Display(Name = "Date of Birth")]
    public DateTime? DateOfBirth { get; set; }

The View:

@Html.TextBoxFor(m=> m.DateOfBirth, "{0:MM/dd/yyyy}", new { @class = "datepicker" })

Any ideas on this?

Thanks.

UPDATE

I overlooked something. The validation actually fails on the server side. So this has nothing to do with jQuery. The ModelState.IsValid == false for me.

nomad
  • 4,366
  • 5
  • 44
  • 60
  • You have MM/dd/yyyy in your view, but mm/dd/yy in your JavaScript. – apohl Feb 04 '14 at 21:34
  • jQuery takes `mm` and .NET `MM` for numeric months. – nomad Feb 04 '14 at 21:40
  • But `yy` is not the same as `yyyy`. – apohl Feb 04 '14 at 21:44
  • For some reason jQuery datepicker uses `yy` for 4-digit year. Using `yyyy` gives something like `20142014`. – nomad Feb 04 '14 at 21:47
  • Ok. For basic JavaScript, `yyyy` is 2014 and `yy` is 14. – apohl Feb 04 '14 at 21:48
  • 1
    You should make the answer in your question a real **Answer** and accept it. But use `@Html.TextBoxFor(m=> m.DateOfBirth, "{0:MM/dd/yyyy}", new { @class = "datepicker" })` - don't attempt to override the model binding features of MVC. –  Jan 23 '15 at 11:47

1 Answers1

1

I found the solution here: ASP.NET MVC3 - DateTime format and it had to do with globalization.

My locale is en-CA and

System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern

gives "dd/MM/yyyy".

So in Web.config under <system.web> I included

<globalization uiCulture="en-US" culture="en-US"/>

So the DateTime format is working for me now.

P.S.

A safe way to pass dates without worrying about specific culture is to use ISO 8601 format - yyyy-MM-dd (or yyyy/MM/dd which also works).

Community
  • 1
  • 1
nomad
  • 4,366
  • 5
  • 44
  • 60