All Articles

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

Published 15 May 2012

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.


Andrew Ford on Twitter
Front End Web Developer from Tauranga, New Zealand

This work is licensed under a Creative Commons Attribution 4.0 International License.