Skip to content
Advertisement

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!

Advertisement

Answer

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.

i suggest you to create an attribute data-id for example, and you put the id of StarDate: so in validator you trap the id of right date

$.validator.addMethod("endError", function (value, element, params) {
    var idstartDate = $(element).attr("data-id");
    var startDate= $(idstartDate).on('input').val();
      :

and you modify the loop:

@{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-id="#StartDate@(i)" data-val="true" data-val-endError="Can't be before start date" required>

    i++;

}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement