I have a DateTime
property in my model, but I'm only interested in the time part:
public class MyModel
{
[Required, DataType.Time]
public DateTime Time
}
In my view, I output it like so:
@Html.EditorFor(model => model.Time)
This used to generate the following html in MVC 3:
<input class="text-box single-line" data-val="true"
data-val-required="The Time field is required."
id="Time" name="Time" type="time" value="" />
Now I'm trying this with MVC 4, and this is the html generated:
<input class="text-box single-line" data-val="true"
data-val-date="The field Time must be a date."
data-val-required="The Time field is required."
id="Time" name="Time" type="time" value="" />
There is an extra attribute data-val-date
added, which results in a client side validation error, because a time (e.g. "10:30") isn't formated as a date.
I suppose this is a bug in MVC 4 (I reported it)? But until it's resolved, is there any way to prevent this attribute from being generated? Or even better, is there a way to let it be generated as a data-val-time
in stead, so I can provide my own client side validation method for time fields?
Validation attributes let you specify validation rules for model properties. The following example from the sample app shows a model class that is annotated with validation attributes. The [ClassicMovie] attribute is a custom validation attribute and the others are built in.
Validates that a property value matches a specified regular expression. Built-in. Remote. Performs a remote validation: you call an action method on the server to validate inputs on the client.
To create a custom validation attributeUnder Add New Item, click Class. In the Name box, enter the name of the custom validation attribute class. You can use any name that is not already being used. For example, you can enter the name CustomAttribute.
To disable client-side validation, set the page's ClientTarget property to 'Downlevel' ('Uplevel' forces client-side validation). Alternatively, you can set an individual validator control's EnableClientScript property to 'false' to disable client-side validation for that specific control.
Not ideal but it will do the job; use JavaScript in your master template to remove the validation:
$(document).ready(function(){
$("input[data-val-date]").removeAttr("data-val-date");
});
Use [DataType("Time")]
instead of [DataType(DataType.DateTime)]
. This will make MVC not treat your variable as DateTime
, and then it will not generate the data-val-date
attribute.
Essentially [DataType("Time")]
makes your variable a custom type. However, you cannot use any other string name for the custom type. MVC tries to detect the underlying type for a custom type. Only when you name your custom type as Time
, it will give up the detection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With