What approach do you recommend for validating a DateTime on the client side in MVC?
Let’s say I have a model with a property named DateOfBirth that is a DateTime, like so.
public class UserModel
{
[DataType(DataType.Date)]
public DateTime DateOfBirth {get;set;}
}
On the View, I have a simple
<%: Html.LabelFor(model=>model.DateOfBirth) %>
<%: Html.EditorFor(model=>model.DateOfBirth) %>
<%: Html.ValidationMessageFor(model=>model.DateOfBirth) %>
<input type="submit" value="Submit" />
I can use either the Microsoft MVC validations or the jQuery validations. How do I get the DateTime to validate client-side?
I realize all the DataTypeAttribute does is provide formatting hints and doesn’t really do any validation (it leaves that part to the ModelBinder).
Basically I want to duplicate what the ModelBinder does when it tries to put the posted value into the model’s DateOfBirth property.
What are your recommendations?
As suggested above, follow Phil Haack’s post on custom validations: http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
Here’s how I would do it:
That should cover things…