Can't validate a form in Bootstrap Modal using JavaScript

809 Views Asked by At

Using the code below I send an email, but if I leave the inputs blank it sends it anyway. I want to validate the form before sending it, to make sure that they are not blank.

j( document ).on( "submit", ".form-horizontal", function() {    
    j.post(this.action, j(this).serialize(), function(){
            //this callback is executed upon success full form submission close modal here
    }, "script");   
    j(this).parent().find('.respuesta').removeClass('oculto'); //to show a success message
    j(this).parent().find('.nota-enviar').addClass('disabled'); //to prevent double click
    setTimeout(function() {j('.modal').modal('hide');}, 2000); //close modal after 2 seconds    
    return false;
});

I tried adapting this example but I could not get it to work. You can see the form at work here. Go to Press Room (Sala de prensa). Display a note, click on Share (Compartir) and click on the mail icon. This will show the Modal with the form.

1

There are 1 best solutions below

1
On BEST ANSWER

There are many plugins to help you with form validation, but for a single form with 4 elements it's probably not needed. Your "Contact form 7" classes should validate the elements, but since you have a few javascript errors on your site (check console) I guess it's not working like it should.

This is a very basic and simple example of how it could be done without plugin dependency (using an alert):

$(document).on("submit", ".form-horizontal", function() {
  var errors = '';
  if ($('input[name="your-name"]').val() == '') errors += ' - Name is required\n';
  if ($('input[name="to-email"]').val() == '') errors += ' - To mail is required\n';
  if ($('input[name="your-email"]').val() == '') errors += ' - Your mail is required\n';
  if ($('textarea[name="your-message"]').val() == '') errors += ' - Message is required\n';
  if (errors != '') {
    alert('The following errors occured:\n' + errors);
  } else {
    alert('form valid, posting...');
    $.post(this.action, $(this).serialize(), function() {
      //this callback is executed upon success full form submission close modal here
    }, "script");
    $(this).parent().find('.respuesta').removeClass('oculto'); //to show a success message
    $(this).parent().find('.nota-enviar').addClass('disabled'); //to prevent double click
    setTimeout(function() {
      $('.modal').modal('hide');
    }, 2000); //close modal after 2 seconds
  }
  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post" action="/echo/html/" class="form-horizontal">
  Name: <input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required required form-control" aria-required="true" aria-invalid="false" />
  <br/>To mail: <input type="email" name="to-email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email required form-control" aria-required="true" aria-invalid="false" placeholder="Dirección de correo electrónico"/>
  <br/>Your mail: <input type="email" name="your-email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email required form-control" aria-required="true" aria-invalid="false" placeholder="Tu dirección de correo electrónico"/>
  <br/>
  <textarea name="your-message" cols="40" rows="3" class="wpcf7-form-control wpcf7-textarea form-control" aria-invalid="false"></textarea>
  <br/>
  <input type="submit" value="enviar" class="wpcf7-form-control wpcf7-submit nota-enviar btn btn-enviar btn-lg pull-left" />
</form>

You could also use a bit more complex solution, looping through the elements and toggling the "required" span:

$('.hide').hide();
$(document).on("submit", ".form-horizontal", function (e) {
    $('.hide').hide();
    var errors = false;
    $('input:not([type=hidden],[type=button],[type=submit]), textarea', e.target).each(function() {
        if ($(this).val() == '') {
           $(this).closest('div').find('span.help-inline').show().css('color','red');
           errors = true;
        }
    });
    if (!errors) {
        $.post(this.action, $(this).serialize(), function () {
            //this callback is executed upon success full form submission close modal here
        }, "script");
        $(this).parent().find('.respuesta').removeClass('oculto'); //to show a success message
        $(this).parent().find('.nota-enviar').addClass('disabled'); //to prevent double click
        setTimeout(function () {
            $('.modal').modal('hide');
        }, 2000); //close modal after 2 seconds
    }
    return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post" action="/echo/html/" class="form-horizontal">
  <div>Name: <input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required required form-control" aria-required="true" aria-invalid="false" /> <span class="hide help-inline">Requerido</span></div>
  <div><br/>To mail: <input type="email" name="to-email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email required form-control" aria-required="true" aria-invalid="false" placeholder="Dirección de correo electrónico"/> <span class="hide help-inline">Requerido</span></div>
  <div><br/>Your mail: <input type="email" name="your-email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email required form-control" aria-required="true" aria-invalid="false" placeholder="Tu dirección de correo electrónico"/> <span class="hide help-inline">Requerido</span></div>
  <br/>
  <div><textarea name="your-message" cols="40" rows="3" class="wpcf7-form-control wpcf7-textarea form-control" aria-invalid="false"></textarea> <span class="hide help-inline">Requerido</span></div>
  <br/>
  <input type="submit" value="enviar" class="wpcf7-form-control wpcf7-submit nota-enviar btn btn-enviar btn-lg pull-left" />
</form>