1

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?

Amarena
  • 11
  • 2
  • Refer https://stackoverflow.com/questions/833997/validate-that-end-date-is-greater-than-start-date-with-jquery – Ajoe Oct 13 '19 at 04:23

1 Answers1

0

You have a for loop for groups and inside it another for loop for tests, which creates a separated div for each test. Move the div creation function to the first loop and edit it accordingly so it won't use the index of tests, then in the second loop add a function that will update inner text or html of the group div. Good luck.

WebMarie
  • 176
  • 2
  • 10