0

We have a bootstrap select (Phasentyp) that is added dynamically via a template.
The template looks like this:

<div class="form-group">
    <div class="form-row">
        <div class="col-4">
            <form-group asp-for="@projektphaseTemplate.PhasenTypId" asp-horizontal="true" asp-label-suffix=" *" data-none-selected-text required></form-group>
        </div>
    </div>
</div>

When adding the template, the select is processed via JavaScript:

// Process the bootstrap selects
projektphase.find('select').each(function(index, element) {
    const el = $(element);

    // Replace name
    let newName = el.attr('name').replace(/projektphaseTemplate/, `Projekt.PPMProjektPhase[${newIndex}]`);
    el.attr('name', newName);

    // Replace ID
    let newId = $(element).attr('id').replace(/projektphaseTemplate/, `Projekt_PPMProjektPhase_${newIndex}_`);
    el.attr('id', newId);

    // Remove all bootstrap-select DOM Stuff for prune select-elements
    el.closest('.bootstrap-select').replaceWith($(element));

    // Reinitialize bootstrap-select
    el.selectpicker({
        noneSelectedText: ''
    });
});

But unfortunately, when saving with the empty option selected, the validation doesn't work.

enter image description here

What is "funny" is, that when I fill out the other required fields and save again, then the validation seems to trigger but with the wrong message:

enter image description here

The HTML looks like this:

enter image description here

What am I doing wrong, that the validation isn't triggered by the first save?

Thanks in advance

xeraphim
  • 4,375
  • 9
  • 54
  • 102
  • A guess: jquery-validation (I assume you use that) works based on elements name attribute, which you probably shouldn't change, or you would have to manually append validation again or else all kind of validation-weirdness can (will) happen. – ferikeem May 28 '21 at 07:40
  • @ferikeem thanks for your comment. Yes we use jquery-validation. The other fields on the screenshot (input and datepicker) are added dynamically via the template as well and the validation works correctly there. I could try appending validation to the select manually, do you know how this is possible? :) – xeraphim May 28 '21 at 07:56
  • 1
    manually adding the validation worked, thanks alot! if you add this as an answer, I'll gladly accept it :-) – xeraphim May 28 '21 at 08:02

1 Answers1

1

You have to reapply jquery's validation to your element, after you changed the name of it.

See here: jQuery - How to dynamically add a validation rule

ferikeem
  • 447
  • 5
  • 13