1
Answer

Validation in javascript

Sushant Torankar

Sushant Torankar

Oct 15
344
1

Hi,

I am using bootstrap modal popup, which have Textbox and Button inside it.I want to apply required field validation on that textbox (For ex. Textbox cannot be empty). But when i give any validation, the modal popup gets close.

The Required Field Validator or javascript validation not working , as modal popup gets close and modal backdrop appears (meaning black background)

 

Any idea which validation or javascript validation can be used, that will appear on modal popup without closing it

 

Thank You !

Answers (1)
2
Tuhin Paul

Tuhin Paul

41 33.5k 311k Oct 16

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">&times;</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
  });
});