MVC2 client/server validation of DateTime/Date using DataAnnotations
- by Thomas
The following are true:
One of my columns (BirthDate) is of type Date in SQL Server.
This very same column (BirthDate) is of type DateTime when EF generates the model.
I am using JQuery UI Datepicker on the client side to be able to select the BirthDate.
I have the following validation logic in my buddy class:
[Required(ErrorMessageResourceType = typeof(Project.Web.ValidationMessages), ErrorMessageResourceName = "Required")]
[RegularExpression(@"\b(0?[1-9]|1[012])[/](0?[1-9]|[12][0-9]|3[01])[/](19|20)?[0-9]{2}\b", ErrorMessageResourceType = typeof(Project.Web.ValidationMessages), ErrorMessageResourceName = "Invalid")]
public virtual DateTime? BirthDate
{
get;
set;
}
There are two issues with this:
This will not pass server side validation (if I enable client side validation it works just fine). I am assuming that this is because the regular expression doesn't take into account hours, minutes, seconds as the value in the text box has already been cast as a DateTime on the server by the time validation occurs.
If data already exists in the database and is read into the model and displayed on the page the BirthDate field shows hours, minutes, seconds in my text box (which I don't want). I can always use ToShortDateString() but I am wondering if there is some cleaner approach that I might be missing.
Thanks