1

Ok I know this question has been asked, and asked, and asked, but I'm missing something and can't seem to figure it out, cause although the datepicker looks right when I try to submit a date such as 13/04/2013 the validation kicks in and says

The field [Date Due] must be a date

I've got a date Editor Template

@model DateTime?

@Html.TextBox("", (Model.HasValue ? 
       Model.Value.ToShortDateString() : 
       string.Empty), new { @class = "datepicker" })

ViewModel

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
[DisplayName("Date Due")]
public DateTime? DueDate { get; set; }

and jQuery

$(document).ready(function () {
    $(function () {
        $(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
    });
});

The datepicker pops up when I enter a field with css class of datepicker, I can select a date such as 13th April 2013 in the datepicker, the value shows up in the textbox but on submit fails validation.

Where am I missing something?

Community
  • 1
  • 1
Simon Martin
  • 4,203
  • 7
  • 56
  • 93

3 Answers3

0

Does the following link help? It implies that the DisplayFormatAttribute you've used only kicks in for displaying the date, and doesn't automatically apply to setting the ViewModel property, unless you specify ApplyFormatInEditMode. Not great with MVCx, so just a guess.

Tom W
  • 5,108
  • 4
  • 30
  • 52
0

The problem with the validation is that jQuery Validate doesn't understand cultures.

For dates, it just calls the javascript: new Date( value ) which fails for ( some ) UK dates.

So, you need to add globalization to the client-side validator - see my answer to this question:

DateTime format according to the culture in MVC

Community
  • 1
  • 1
Nick Butler
  • 24,045
  • 4
  • 49
  • 70
0

I can't take any credit for the answer to my problem; but the solution that worked for me was in the accepted answer for MVC DateTime validation - UK Date format and was

to overload unobtrusive JavaScript validation method for date

The linked post has script that worked for me as soon as I dropped it into my scripts file.

I'm not sure if this is required because as @Nicholas Butler says

jQuery Validate doesn't understand cultures.

or if it's because I've used [DisplayFormat(DataFormatString = "{0: dd MMM yyyy}")] to make the dates appear as 20 Apr 2013 instead of 20/04/2013 as pointed out

{0:dd/mm/yyyy} should be {0:dd/MM/yyyy} because mm means minutes, not months:

so could be that the difference between the date formats was causing my problem

Community
  • 1
  • 1
Simon Martin
  • 4,203
  • 7
  • 56
  • 93