2
Prevent form submission on invalid input -
Check that you prevent the form from being submitted if the validation fails by using JavaScript or jQuery to handle the submit event of the form. This way, the modal won't close unless the validation is successful.
<!-- Button to open modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Open Modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form id="modalForm" novalidate>
<div class="modal-header">
<h5 class="modal-title" id="myModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="exampleInput">Enter Text</label>
<input type="text" class="form-control" id="exampleInput" required>
<div class="invalid-feedback">
This field is required.
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
$(document).ready(function () {
$('#modalForm').on('submit', function (event) {
// Prevent form submission if validation fails
if (this.checkValidity() === false) {
event.preventDefault(); // Prevent submission
event.stopPropagation(); // Stop the modal from closing
}
$(this).addClass('was-validated'); // Show validation styles
});
});
