1. Your client side validation is not working. You are seeing error message after the form is submitted - means client side validation is not working properly. To make the client side validation work, ASP.NET MVC assumes that you have jquery.validate.js
and jquery.validate.unobtrusive.js
referenced on the page. You can download them using NuGet Package Manager on your Visual Studio.
2. Date field is not being validated. You are expecting the DisplayFormat
to validate the date format for you. But actually it does not. That is more of about displaying your date on the View.
In order to validate the date format, you need to use your own custom Attribute
. Or you can simply use RegularExpression
attribute. The most simple example looks like this:
[RegularExpression(@"\d{1,2}/\d{1,2}/\d{2,4}\s\d{1,2}:\d{1,2}", ErrorMessage = "")]
Or if you want to make a custom attribute, then:
public class DateFormatValidation : ValidationAttribute{
protected override bool IsValid(object value){
DateTime date;
var format = "0:dd/MM/yyyy HH:mm"
bool parsed = DateTime.TryParseExact((string)value, format, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out date)
if(!parsed)
return false;
return true;
}
}
Then use it like:
[DataType(DataType.DateTime, ErrorMessage = "Invalid Datetime")]
[DateFormatValidation]
[Display(Name = "Start Datetime")]
public DateTime? StartDateTime { get; set; }