I’m using the stock function to display a date range in an MVC 4 Razor view. The start/end dates are part of a filter in my model class. I want the start/end dates to be optional.
When I submit the form without the start/end filled in it triggers a “Required Field” validation check displaying these lovely messages:
- The Installed Date field is required.
- The InstalledDateEnd field is required.
Yet the form does submit and my filter runs and returns results.
<script>
$(function () {
$("#InstalledDateStart").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onSelect: function (selectedDate) {
$("#InstalledDateEnd").datepicker("option", "minDate", selectedDate);
}
});
$("#InstalledDateEnd").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onSelect: function (selectedDate) {
$("#InstalledDateStart").datepicker("option", "maxDate", selectedDate);
}
});
});
</script>
I tried telling the Model that the fields were not required, didn’t help:
[Display(Name = "Installed Date")]
[Required(AllowEmptyStrings = true)]
public DateTime InstalledDateStart { get; set; }
[Required(AllowEmptyStrings = true)]
public DateTime InstalledDateEnd { get; set; }
And this is the markup in the view:
@using (Html.BeginForm("Filter", "Search"))
{
<div class="divSearchBlock">
<br style="clear:left;" />
<div>
<b>@Html.DisplayNameFor(model => model.ConstraintModel.InstalledDateStart)</b>
@Html.TextBox("InstalledDateStart", null, new { @class = "divCellContent" })
<b>-</b>
@Html.TextBox("InstalledDateEnd", null, new { @class = "divCellContent" })
</div>
<input type="submit" value="Submit"/>
</div>
}
What in the world is causing the fields to be required?
DateTimes are not strings. SoAllowEmptyString=truemakes no sense. If you want yourDateTimes to be nullable declare your model as:You need the
?is important because without this theDateTimewill end up asDateTime.MinValue