首页 > 解决方案 > 带有 JQueryValidation 的表单不运行 validate() 函数

问题描述

我在 Bootstrap Modal 中有一个表单。此表单有 2 个简单的输入:一个用于问题,另一个用于 URL 链接。它使用 jQueryValidation ( http://jqueryvalidation.org ) 执行表单验证,并使用 jQuery Ajax 提交表单操作。

问题: .validate() 函数不工作/运行/执行。即使只有调试选项的简短形式也不会运行:

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

例如,如果我将 textarea (name="form_question") 留空,则 validate() 不会根据声明的规则发出警报。

是什么阻止了 validate() 运行?

重要提示:除了 validate() 之外的所有脚本都运行正常,甚至 jQuery.ajax() 也成功运行(将数据从表单插入 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>

脚本:

<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>

标签: jqueryjquery-uibootstrap-4jquery-validatebootstrap-modal

解决方案


您需要致电valid()以突出显示/提醒用户。将您的实现更改为这样的

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);
        }
      });
    }
  });
});

此处,仅当表单有效时才会调用 ajax POST 请求方法。

参考:https ://jqueryvalidation.org/valid/


推荐阅读