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:

function (value, element, params) {

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

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


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!

Read more here: https://stackoverflow.com/questions/66264151/jquery-validate-dynamically-added-input-fields-against-other-dynamically-added-i

Content Attribution

This content was originally published by Alaeddine Hedhly at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: