Search code examples
javascripthtmlasp.net-corebootstrap-4bootstrap-select

Bootstrap select required validation not working properly


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


Solution

  • 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