5

I'm a newbie to MVC 3 and JQuery Validation so any help I can get here will be very much appreciated.

My devleopment platform is .NET MVC 3 website. I'm using the built in unobtrusive javascript for form validation. Is there a way to change the date to a different format for a valid date. As far as I can tell, the valid format is dd/mm/yy. Is it possible to change the valid date format to something like "Apr 3, 2012"?

My view model has a field

[Required]
DateTime OrderDate { get; set; }

I know that MVC 3 is using jquery validation under the hood so I'm thinking the solution will require a change to jquery validate and also not sure how to hook it up to MVC so it works like all the other built in data validations using data annotations.

Thank you.

user1279723
  • 51
  • 1
  • 2

2 Answers2

8

When you use client side validation for date, you have to override the jQuery validation for date as well.

$.validator.methods.date = function (value, element) {
    return this.optional(element) || Globalize.parseDate(value, "MMM dd, yyyy") !== null;
}

You have to reference the Globalize library and the appropriate culture in your HTML head. Download from https://github.com/jquery/globalize.

Jeow Li Huan
  • 3,758
  • 1
  • 34
  • 52
1

If you wanted to change the format of Order Date you would do so with the DisplayFormat annotation:

[DisplayName("Order Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy}")]
[Required]
DateTime OrderDate { get; set; }

Where the DataFormatString is your desired date time format.

Jesse
  • 8,223
  • 6
  • 49
  • 81
  • Thank you, but it doesn't work. My date format as outlined above is "Mar 18, 2012" so I slightly tweaked your suggestion with my format, but the validation still fails for the date. [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MMM dd, yyyy}")] – user1279723 Mar 20 '12 at 19:50