JQuery validate dynamically added input fields against other dynamically added input fields

I have multiple pairs of input fields for start and end dates:

@foreach (var exam in exams){
        <input type="date" data-val="true" required id="StartDate" value="exam.StartDate">
        <input type="date" data-val="true" data-val-endError="Can't be before start date" required>
}

I’m using jQuery’s validator.AddMethod to validate that the end date is after the starting date:

$.validator.addMethod("endError",
function (value, element, params) {

    var startDate = $("#StartDate").on('input').val();

    if (value.toString() <= startDate) {
        return false;
    } else {
        return true;
    }
});

$.validator.unobtrusive.adapters.addBool("endError");

The problem is the validation is always comparing the end dates to the first starting date. I want each end date to be compared to it’s relevant starting date.

I’m still a newbie in javascript but I know that this is probably caused by the id being the same for all the startDate inputs, which is illegal html.

Is there a way to fix this?
Thanks!

1 thought on “JQuery validate dynamically added input fields against other dynamically added input fields”

Leave a Comment