0

I have a form inside a Bootstrap Modal. This form has 2 simple inputs: one for a question and another for a URL link. It uses jQueryValidation (http://jqueryvalidation.org) to perform a form validation, and a jQuery Ajax to submit the form action.

Problem: .validate() function is not working/running/performing. Even a short form with only debug option does not run:

$("#form_pergunta").validate({
                debug: true });

For example, if I left textarea ( name="form_question") blank, validate() does not alert, based on rules declared.

What does prevent validate() to run ?

Important: All script but validate() run ok, with even jQuery.ajax() running with success ( insert data from form into Mysql ok) .

HTML

    <div class="modal fade bd-example-modal-lg" id="myModal_Pergunte" tabindex="-1" role="dialog" >
  <div class="modal-dialog modal-lg">

     <!-- Modal content-->
     <div class="modal-content">
        <div class="modal-header">
           <h5 class="modal-title">Title</h5>
           <button type="button" class="close" data-dismiss="modal">X</button>
       </div>
       <div class="modal-body">

        <form method="POST"  action="{{ url('/question')}}" id="form_pergunta">
            {{ csrf_field() }}

            <div class="form-group">
             <label for="formGroupTextArea">What is your question? </label>
             <textarea type="text" class="form-control" id="formGroupTextArea" placeholder="Faça sua pergunta utilizando até 250 caracteres." rows="8" maxlength="250" name="form_question" required></textarea>
             <h6 class="float-right pt-1 text-muted" id="count_message"></h6>

         </div>
         <div class="form-group">
             <label for="formGroupInputUrl">Link opcional</label>
             <input type="text" class="form-control" id="formGroupInputUrl" placeholder="Caso deseje, inclua um link que faça referência a pergunta" name="form_url" maxlength="250">
         </div>
     </div> 
     <div class="modal-footer">
         <button type="button" class="btn btn-primary" name="btn_submit" id="ajaxSubmit" >Submit</button>
     </div>

     </form>
</div>
</div>
</div>

JS:

<script>
$(document).ready(function(){
    $('button#ajaxSubmit').click(function(e){

         e.preventDefault();

        $("#form_pergunta").validate({
           rules: {
                form_question: {
                    required: true,
                    minlength: 10,
                    maxlength: 250
                },
                form_url: {
                    required: false,
                    minlength: 0,
                    maxlength: 250,
                    nowhitespace: true
                }
            },
            messages: {
                form_question: {
                    required: "Por favor, digite sua pergunta.",
                    minlength: "Esta não parece ser uma pergunta válida.",
                    maxlength: "A pergunta não pode ter mais que 250 caracteres."

                },
                form_url: {
                    maxlength: "O link não pode ter mais que 250 caracteres.",
                    nowhitespace: "Não deve haver espaços no endereço digitado."
                }
            }    
        });

       $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
          }
       });
       jQuery.ajax({
          url: "{{ url('/question') }}",
          method: 'POST',
          data: $('#form_pergunta').serialize(),
          success: function(result){
            $('#form_pergunta')[0].reset();
            $('#myModal_Pergunte').modal('toggle');
            msgbox_Text = "Sua pergunta foi incluída com sucesso!" ;
            $("#msgbox_alertmsg").append(msgbox_Text);
            $('#myModal_MsgBox').modal('show');

          },
          error: function (data, textStatus, errorThrown) {
              console.log(data);
          },
      });
       });
    });

</script>

Scripts:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
Paulo
  • 100
  • 1
  • 12
  • 1
    Your first mistake was putting `.validate()` within a `click` handler; you're not understanding the purpose of `.validate()`. It's not a trigger... it's the initialization of the plugin and does not go in a `click` handler.. Second mistake is not using a `type="submit"` button. – Sparky Aug 16 '18 at 21:15

1 Answers1

0

You need to call valid() in order to highlight/alert user. Change your implementation to something like this

jQuery

$(document).ready(function() {
  $.ajaxSetup({
    headers: {
      "X-CSRF-TOKEN": $('meta[name="_token"]').attr("content")
    }
  });

  $("#form_pergunta").validate({
    rules: {
      form_question: {
        required: true,
        minlength: 10,
        maxlength: 250
      },
      form_url: {
        required: false,
        minlength: 0,
        maxlength: 250,
        nowhitespace: true
      }
    },
    messages: {
      form_question: {
        required: "Por favor, digite sua pergunta.",
        minlength: "Esta não parece ser uma pergunta válida.",
        maxlength: "A pergunta não pode ter mais que 250 caracteres."
      },
      form_url: {
        maxlength: "O link não pode ter mais que 250 caracteres.",
        nowhitespace: "Não deve haver espaços no endereço digitado."
      }
    }
  });

  $("button#ajaxSubmit").click(function(e) {
    if ($("#form_pergunta").valid()) {
      jQuery.ajax({
        url: "{{ url('/question') }}",
        method: "POST",
        data: $("#form_pergunta").serialize(),
        success: function(result) {
          $("#form_pergunta")[0].reset();
          $("#myModal_Pergunte").modal("toggle");
          msgbox_Text = "Sua pergunta foi incluída com sucesso!";
          $("#msgbox_alertmsg").append(msgbox_Text);
          $("#myModal_MsgBox").modal("show");
        },
        error: function(data, textStatus, errorThrown) {
          console.log(data);
        }
      });
    }
  });
});

Here, ajax POST request method will be called only if the form is valid.

Reference: https://jqueryvalidation.org/valid/

Soham
  • 1,281
  • 7
  • 15
  • You do not need a `click` handler! For Ajax, the plugin includes a `submitHandler` callback function that automatically fires when the form is valid and the button is clicked. Read: http://jqueryvalidation.org/validate/#submithandler – Sparky Aug 16 '18 at 21:23