开发者

MVC2 client/server validation of DateTime/Date using DataAnnotations

The following are true:

  • One of my columns (BirthDate) i开发者_如何学Cs 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:

  1. 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.

  2. 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


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" })%>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜