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!

6 thoughts on “JQuery validate dynamically added input fields against other dynamically added input fields”

  1. the problem with your code is you are referencing always the same id StartDate
    so its normal the validation is always from the same startdate. When you have lot of same id the search of id stops always at the first.

    @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>
    }
    

    and you have the same id for different tag, its not good in html.

    in your validator, you reference the StartDate id

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

    one solution will be to create an id indexed :

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

    you adapt the validator to trap the right id.

    Reply

Leave a Comment