I am rendering out a DateTime field from my view model into two separate form fields (Date and Time). I have this line of code in my view:
@Html.TextBox("EndTime.Date", Model.EndTime.ToShortDateString())
which renders as:
<input data-val="true" data-val-date="The field Date must be a date."
data-val-required="The Date field is required." id="StartTime_Date"
name="StartTime.Date" type="text" value="29/09/2012">
- Why is this input field having the data-* attributes added to it?
- Why does it even think it is a date?
An interesting side-effect of this unexpected validation is it causes the field to be validated as a date (which is what I want by coincidence), but jquery is deciding to use the wrong date format so I get the error:
“The field Date must be a date.”
UPDATE:
Turns out the “wrong date format” error was caused by a bug in Chrome. Because the JQuery Validation library validates a date by creating a new Date(), and because Chrome always seems to parse dates as en-US (totally ignoring the locale /language settings) it was failing when I put in en-UK dates.
Because you have enabled unobtrusive validation in your application. As default, the MVC validation system enables client-side validations of both required & datatype for value types(integer, datetime).
When you pass a string to the
Html.TextBoxhelper method it checks if theModelcontains any property with that name and in your case theModelhas a property with nameEndTimeand which is of typeDateTime.You are passing
EndTime.Datethat still represents the typeDateTime(DateTimehas a propertyDatewhich is of typeDateTimecontains only the date component) and so the two validations are enabled by MVC.I would suggest you two create two different properties to store the date and time.