0

In all my projects, I have jQuery date pickers that format the date dd-MMM-yyyy which both users worldwide and the DateTime.parse method understand perfectly - sadly this does not appear to be the case for data annotation validation! I have my data annotation as below:

    [Display(Name = "Date of Birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:d-MMM-yyyy}", ApplyFormatInEditMode = true)]
    [Required(ErrorMessage = "You must enter a date of birth.")]
    public DateTime dob { get; set; }

And my form refuses to submit with the error as below:

Date field

Does anyone know how I can make it validate, accept and modelbind a date value in this format?

Jimbo
  • 22,379
  • 42
  • 117
  • 159

1 Answers1

0

You could write a custom model binder for the DateTime type as I have shown here that will use the format defined in the [DisplayFormat] attribute when parsing back a DateTime field from the request. By the default the model binder uses the CultureInfo setting of the current thread or the value you have configured in the <globalization> element of your web.config. If you set it to auto, then ASP.NET will use the client Accept-Language request header to adjust the culture info.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks Darin, problem is that the form containing these date fields wont even submit because of the bloody *client side* validation that fails as well. Ideas? – Jimbo Jul 05 '12 at 12:16
  • Who is performing the client side validation? The MS unobtrusive js library doesn't do that. It seems that you are performing some custom validation with the jQuery UI dateicker plugin. Can you show your code? – Darin Dimitrov Jul 05 '12 at 14:58