Jquery 表单验证 - 如何在验证之前不执行代码

Jquery form validation - How not to execute code before validating

本文关键字:验证 执行 代码 表单 Jquery      更新时间:2023-09-26

我写了一个带有一些计算的小表单。现在,使用按钮单击事件完成计算。

  $('a#check_var').click(function() {
    // the below call the form validation  
    $("#bet_cal_form").valid();
          <- My code here ->
  });

现在一切正常,问题是我不希望我的代码执行,除非表单验证中没有错误。目前我收到错误消息,但我的代码也被执行了。

当然

,请使用if语句。

if ($("#bet_cal_form").valid()) {
    // Stuff that should only be done if form is valid
}

您需要一个 if 和 取消链接,并且由于所有 ID 都需要是唯一的,因此您不需要选择器中的 a

$(function() {
  $("#check_var").on("click",function(e) {
    e.preventDefault();
    // the below call the form validation  
    if($("#bet_cal_form").valid()) {
      <- My code here ->
    }
  });
});