Reputation: 5998
The following are true:
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
Upvotes: 1
Views: 2322
Reputation: 24754
1: This is easily solved by changing DateTime to be non-nullable, meaning the datetime value entered must be parse-able and therefore valid, and then use the:
[DataType(DataType.Date)]
attribute instead of the regular expression. This will make sure the field is required and must be parse-able.
2: This is a templating issue. The easy way is to create a custom Date.ascx template inside of /Views/Shared/EditorTemplates that calls ToShortDateString() and will hook up your jquery datepicker.
This is what mine looks like:
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%
string displayText = string.Empty;
if (Model != null)
{
if (DateTime.Parse(Model.ToString()) != DateTime.MinValue)
displayText = DateTime.Parse(Model.ToString()).ToShortDateString();
}
%>
<%= Html.TextBox("", displayText, new { @class = "date-box" })%>
Upvotes: 1