Time validation in ASP.Net MVC using a regular expression.

Just a quick tip for Time validation in ASP.Net MVC for your data model using a regular expression.

Place the following in your model:


[DisplayFormat(ApplyFormatInEditMode = true,
DataFormatString = "{0:HH:mm}")]
[RegularExpression(@"^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$", ErrorMessage = "Invalid time.")]
public DateTime? YourDateTime { get; set; }


This will perform the validation for 24 hour time in the format HH:mm

A big thanks to Markus Wulftange (Gumbo on Stack Overflow) for the tip. Here is his original answer he posted.