如果使用Jquery Validator存在验证错误,如何避免或禁用表单提交

时间:2016-09-06 20:06:17

标签: javascript jquery forms validation jquery-ui

我实际上面临使用JQUERY Validator进行表单验证的问题。表单即使在字段上有验证错误也会提交。我不确定当字段上存在验证错误时,我们如何禁用或不允许提交表单?我相信当存在验证错误时,bootstrap验证器会禁用该按钮。虽然在我的情况下我使用JQUERY VALIDATOR,所以表单正在提交并调用我正在调用提交的ajax调用。请帮忙!

form id="myform" class="form-horizontal" role="form" action="processAccount" method="post">
                    <h2><b style="color:#1E90FF;">Account</b></h2>
                    <div class="form-group">
                        <label for="Account Number" class="col-sm-3 control-label">Account Number</label>
                        <div class="col-sm-9">
                            <input type="text" id="accountNumber"  name="accountNumber" placeholder="Account Number" class="form-control" autofocus required />
                        <!--<span class="help-block">Last Name, First Name, eg.: Smith, Harry</span>-->                    
                    </div>
                    </div>

                    <div class="form-group">
                        <label for="Company Number" class="col-sm-3 control-label">Company Number</label>
                        <div class="col-sm-9">
                            <input type="number" min="1" id="companyNumber" name="companyNumber" placeholder="Company Number" class="form-control" value=${companyNumber} required />
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-sm-9 col-sm-offset-3">
    <!--                         <button type="submit" class="btn btn-info btn-block" onclick="doAjaxPost()">Search</button>
     -->                        
                            <input type="button" style=" font-size: 18px;font-weight: bold;  font-family: cursive;" id="processbutton" class="btn btn-info btn-block" value="Load" onclick="doAjaxPost()">

                                <div id="info" style="color: green; font-weight: bold;" font-size:380%;></div>      

    <%--                        <p ><strong>${message}</strong></p>
     --%>                                    
                        </div>
                      </div>

                </form> <!-- /form -->

<script>
$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin

        rules: {
            accountNumber: {
                required: true,
                minlength: 7,
                maxlength: 7,
                digits: true

            },
            companyNumber: {
                required: true,
                digits: true

            },
            submitHandler: function (form) {
                console.log("Submitted!");
                form.submit();
            }
        }
    });

});

    </script>



<script type="text/javascript">
function doAjaxPost() {  
      // get the form values  
      var accountNumber = $('#accountNumber').val();
      var companyNumber = $('#companyNumber').val();
      var token = $("meta[name='_csrf']").attr("content");
      var header = $("meta[name='_csrf_header']").attr("content");
      var num = 1;
      $.ajax({  
        type: "POST",  
        url: "./processAccount",  
       cache: false, 
        data: "accountNumber=" + accountNumber + "&companyNumber=" + companyNumber,  
       beforeSend: function(xhr) {
           xhr.setRequestHeader(header, token);
       },
        success: function(response){  
          // we have the response  
          $('#info').html(response);
          $('#accountNumber').val('');
          if(companyNumber!=1)
              {
          $('#companyNumber').val(num);
              }
        },  
        error: function(e){  
          alert('Error While Request: ' + e);  
        }  
      });  
    }  
</script>

在JQUERY Validation块下添加了SubmitHandler方法,但是在请求方法&#39; POST&#39;不支持

submitHandler: function (form) {
                console.log("Submitted!");
                // get the form values  
              var accountNumber = $('#accountNumber').val();
              var companyNumber = $('#companyNumber').val();
              var token = $("meta[name='_csrf']").attr("content");
              var header = $("meta[name='_csrf_header']").attr("content");
              var num = 1;
              $.ajax({  
                type: "POST",  
                url: "./processAccount",  
              dataType: "json",
              contentType: 'application/json',
               cache: false, 
                data: "accountNumber=" + accountNumber + "&companyNumber=" + companyNumber,  
               beforeSend: function(xhr) {
                     xhr.setRequestHeader(header, token);
                 },
                success: function(response){  
                  // we have the response  
                  $('#info').html(response);
                  $('#accountNumber').val('');
                  if(companyNumber!=1)
                      {
                  $('#companyNumber').val(num);
                      }
                },  
                error: function(e){  
                  alert('Error While Request: ' + e);  
                }  
              }); 
              form.submit();
            }
          }
    });
});

3 个答案:

答案 0 :(得分:1)

将提交按钮更改为type="submit"并删除点击处理程序。

如果您想通过AJAX发送它,您仍然可以在submitHandler回调中执行此操作。

说明:将点击处理程序设置为doAjaxPost(),您可能会绕过验证,submitHandler代码永远不会被执行。

此外,您还有其他错误。 submitHandler应该是rules而不是孩子的s !!它不会被称为你使用它的方式。改为使用它:

$('#myform').validate({ // initialize the plugin
    submitHandler: function (form) {
         console.log("Submitted!");
         form.submit(); // default form submitting
    },
    rules: {
        accountNumber: {
            required: true,
            minlength: 7,
            maxlength: 7,
            digits: true
        },
        companyNumber: {
            required: true,
            digits: true
        }
    }
});

另请参阅API文档https://jqueryvalidation.org/documentation/

要通过AJAX发送,您应该可以致电doAjaxPost()而不是form.submit(); - 在这个位置验证已经发生。

编辑:从OP发出的声音 - 这里是如何使用他的自定义AJAX调用来编写它:

submitHandler: function (form) {
      console.log("Submitted!");
      doAjaxPost(); // custom AJAX call
}

答案 1 :(得分:0)

我怀疑除了验证结果之外还调用了doAjaxPost()方法。这个方法里面有什么?

您能否使用(项目页面,文档页面......)识别jquery validate plugin?

答案 2 :(得分:0)

您可以这样做,只需添加以下选项:

$("#myform").validate({
  success: function() {
    $("button[type='submit']").prop("disabled",false);//enable your submit if success
  },
  invalidHandler: function(){
   $("button[type='submit']").prop("disabled",true); // disable your submit if there is any errors
    return false; //Disable post
  }
});

更多信息https://jqueryvalidation.org/validate/