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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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}")]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.