title: Bootstrap 4 client validation before ajax submit
body: <p>I have a form (see it below). We follow bootstrap 4 on a project therefore I prefer to re-use as much as possible and do not write my own code where it is not needed.</p>
  
  <p>When user press Submit button I do AJAX post request and as a response I get JSON object with some information. Based on that response I have to do some logic.</p>
  
  <pre><code>&lt;form name="signin" class="js-form-submit needs-validation" action="/signin"&gt;
    &lt;div class="form-group"&gt;
      &lt;label for="username"&gt;User Name&lt;/label&gt;
      &lt;input class="form-control" id="username" name="username" autofocus&gt;
    &lt;/div&gt;
    &lt;div class="form-group"&gt;
      &lt;label for="password"&gt;Password&lt;/label&gt;
      &lt;input type="password" class="form-control" id="password" name="password" &gt;
    &lt;/div&gt;
    &lt;button type="submit" class="btn btn-primary mb-2"&gt;Submit/button&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>Now I want to make client-side validation (and I prefer to use bootstrap if possible). They have an example but it works with normal submit but not with AJAX and I'm curious how can I perform bootstrap 4 client-side validation before my AJAX call?</p>
  
  <pre><code>// Example starter JavaScript for disabling form submissions if there are invalid fields
  (function() {
    'use strict';
    window.addEventListener('load', function() {
      // Fetch all the forms we want to apply custom Bootstrap validation styles to
      var forms = document.getElementsByClassName('needs-validation');
      // Loop over them and prevent submission
      var validation = Array.prototype.filter.call(forms, function(form) {
        form.addEventListener('submit', function(event) {
          if (form.checkValidity() === false) {
            event.preventDefault();
            event.stopPropagation();
          }
          form.classList.add('was-validated');
        }, false);
      });
    }, false);
  })();
  </code></pre>
  
  <p><a href="https://getbootstrap.com/docs/4.0/components/forms/#custom-styles" rel="noreferrer">https://getbootstrap.com/docs/4.0/components/forms/#custom-styles</a></p>
  
  <p>Could somebody point me on a direction or maybe give a snippet of code.</p>
  
  <p>Thanks.</p>