Getting format exceptions from a property of type DateTime is very annoying issue. It is a fairly common issue when working with validation on DateTime.
DataAnnotaions works on server side and to take their full advantage you need to add ModelState.IsValid() in your controller.
public ActionResult Index(MyViewModel model)
{
if(ModelState.IsValid())
{
// valid data received...
}
else
{
// Invalid data, add model error here and return view...
}
}
If you to make these work on client side then you need to include two additional JavaScript files in your code i.e. jquery.validate.js and jquery.validate.unobtrusive.js along with jQuery core library. By Default all of these files comes in basic MVC project and included in Layout.
It is important to note the order of including these files. jQuery core should always be at the top followed by validation libraries.
- jquery.js
- jquery.validate.js
- jquery.validate.unobtrusive.js
Make sure the validation flags are turned on in web.config file of
MVC project. Go to this file and locate the following and set them
true if they are false.
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
This should setup your validations to work on client side. You can decorate the model property with the RegularExpression.
[Required]
[RegularExpression("^(([0-2]?[0-9]|3[0-1])/([0]?[1-9]|1[0-2])/[1-2]\d{3}) (20|21|22|23|[0-1]?\d{1}):([0-5]?\d{1})$", ErrorMessage = "Invalid date")]
public string DateTimeStart { get; set; }
This will validate the datetime in dd-mm-yyyy hh:mm format.
Besides in this case you can make your property a string type also because regular expression will take care of your date format.
Apart from this, you can also create your custom DataAnnotation.