Validation of DateTime in UK format in C# MVC

In a recent project I was using the bootstrap datetime picker from here:

http://eonasdan.github.io/bootstrap-datetimepicker/

And had it on my view like this:

@Html.TextBoxFor(m => m.EmailDate, “{0:dd/MM/yyyy HH:mm}”, new { @class = “form-control txtModal” })

@Html.ValidationMessageFor(model => model.EmailDate)

Every time I tried to submit the form I would get a jquery validation error telling me that EmailDate was not a valid date. There was a lot of material relating to this problem on Stackoverflow but much was erroneous or misleading. Many suggest that you use data annotations on the model to set the display format…but this only helps a bit if you use an EditorFor rather than a TextBoxFor helper function in the view. It does not get round the validation problem.

The essential problem to overcome is that be default jquery validation expects a date to be in US format (mm/dd/yyy). So, we have to extend the validation logic to allow for UK date formats (dd/mm/yyyy). Once we have done that, we need to cater for the time element that may have been selected using the datetimepicker. The solution below will work for a datepicker or a datetimepicker and can be altered to match any date format as it uses Regex expressions. Add the following to your view script section:

$.validator.addMethod(“date”, function (value, element) {
var stamp = value.split(” “);
var d = new Date();
var validDate = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/.test(stamp[0]);
var validTime = /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(stamp[1]);
return this.optional(element) || (validDate && validTime);
}, “Please enter a valid date and time.”);

We split the datetime value in to two parts and Regex each part separately and then combine the results to avoid having an invalid date and time parts.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s