I want to add custom validation (only in one view) for two @Html.EditorFor date inputs so that the start date would have to be less than or equal to the end date. This is my code:
<div class="form-group">
@Html.LabelFor(model => model.DateFrom)
@Html.EditorFor(model => model.DateFrom, new { htmlAttributes = new { @class = "form-control", @id = "StartDate", @required = "required" } })
@Html.ValidationMessageFor(model => model.DateFrom, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.DateTo)
@Html.EditorFor(model => model.DateTo, new { htmlAttributes = new { @class = "form-control", @id = "EndDate", @required = "required" } })
@Html.ValidationMessageFor(model => model.DateTo, "", new { @class = "text-danger" })
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function () {
$("#StartDate").add("#EndDate").change(function () {
if ($("#StartDate").val() > $("#EndDate").val() && $("#StartDate").val().length != 0 && $("#EndDate").val().length != 0) {
alert($("#StartDate").val());
$("#EndDate")[0].setCustomValidity('Invalid Range');
}
});
});
</script>
I expect to add a validator that will display my custom message with @ Html.ValidationMessageFor if the date range would be incorrect and it will set any of inputs as invalid (thus blocking form submit). I tried setCustomValidity () but it doesn't work (nothing happens). What am I doing wrong?