Skip to content

Close static backdrop modal on failed client-side validation when submitting

Before submitting a form the user clicks a button to open a “confirm” modal. When pressing “Apply” in the modal client-side validation fires and validates all fields. So far so good, but if validation fails the modal does not close and I cannot work out how.

I have tried to attach an eventhandler to the submit button and then call myModal.hide(), but nothing happens. I suspect some other bootstrap js code is in conflict, but I cannot work out what to do?

I have manually tried to revert .show() by removing classes from and modal-backdrop, but then I end up preventing the modal to load again (after correction of the validation mistakes)

I’m using Bootstrap 5, beta 3.

<form method="post">
    <div class="mb-1">
        <div class="form-floating pb-0">
            <input type="text" class="form-control" asp-for="Input.Title" placeholder="Title">
            <label asp-for="Input.Title">Event title</label>
        <span asp-validation-for="Input.Title" class="text-danger"></span>
    <button type="button" class="btn" data-bs-toggle="modal" data-bs-target="#confirmStaticModal">

    <div class="modal fade" id="confirmStaticModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="confirmStaticModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirmStaticModalLabel">Apply</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                <div class="modal-body">
                    <p>Are you sure?</p>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
                    <input type="submit" class="btn btn-success" value="Apply" id="confirmApplicationButton" />

JS Code to add event handler

document.getElementById("confirmApplicationButton").addEventListener("click", (event) => {
    var modal = new bootstrap.Modal(document.getElementById("confirmStaticModal"));


By using new bootstrap.Modal() in this way, you’re creating an additional, new Bootstrap modal using elements from a pre-existing Bootstrap modal. Having two different modals attached to the same HTML elements causes a conflict.

The correct way to get a reference to an already created modal is via .getInstance() as in:

var modal = bootstrap.Modal.getInstance(document.getElementById("confirmStaticModal"));