I have lots of forms in my MVC3 application that require the user to input dates.
The requirement of the date given could be one of many cases, i.e a Date with a time, just a date, a date in the past, a date and time in the past, a date in the future, a date and time in the future etc…
So, at the moment I give the a different class depending in what is required. For example….
$("input.input-date-past").datepicker({ numberOfMonths: 1, showButtonPanel: true, maxDate: -0 });
…configures a date picker that restricts the users choice to date in the past only.
All this is working OK, but I was wondering if there was a better way.
I’m thinking that I could give the view model properties an attribute that would define what type of input was required. i.e
[Required]
[PastDate]
public DateTime SomeDateFromThePast { get; set; }
[Required]
[FutureDate]
public DateTime SomeDateFromTheFuture { get; set; }
[Required]
[FutureDateTime] // Requires a time to be given i.e "01/01/2012 09:00"
public DateTime SomeDateTimeFromTheFuture { get; set; }
etc..
Then in an Shared/EditorTemplate with @model System.DateTime, which will interrogate the attributes given to the property and set the class of the as required.
Does that sound OK? Or does it stink?
If OK, how do you interrogate the attributes given to the property?
If it stinks, any other suggestions?
Many thanks,
ETFairfax.
You can write your own hooks into ASP.NET MVC’s unobtrusive validation to write to
data-attributes.This tutorial should get you started.
http://www.codeproject.com/Articles/275056/Custom-Client-Side-Validation-in-ASP-NET-MVC3