You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AJAX提交表单时表单验证失效问题求助

表单验证未生效,点击提交直接执行AJAX调用

我有一个通过AJAX将数据提交到Google Sheets的表单,原本功能正常,但添加自定义JS表单验证后,验证逻辑被完全忽略,点击提交按钮直接就触发了AJAX请求。我之前习惯用PHP做验证,刚接触JS验证,不知道哪里出问题了。

我的HTML表单代码:

<!DOCTYPE html> 
<html class="no-js" lang="en"> 
<head> 
    <title>MooWoos Stall Booking</title> 
    <meta http-equiv="x-ua-compatible" content="ie=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:400,800"> 
    <link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> 
    <!--build:css css/styles.min.css--> 
    <link rel="stylesheet" href="/css/bootstrap.css"> 
    <link rel="stylesheet" href="/css/style.css"> 
    <!--endbuild--> 
</head> 
<body> 
    <!-- Page Content --> 
    <div class="container"> 
        <nav class="navbar navbar-toggleable-md navbar-light"> 
            <a class="logo"><img src="assets/logo_opt.png"></a> 
        </nav> 
        <hr> 
        <div class="modal fade" id="redirect_page" role="dialog"> 
            <div class="modal-dialog"> 
                <div class="modal-content"> 
                    <div class="form-horizontal"> 
                        <div class="modal-body"> 
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
                            <div id="user_msg" align="left">Booking successful! Redirecting to PayPal... </div> 
                        </div> 
                    </div> 
                </div> 
            </div> 
        </div> 
    </div> 
    <div class="row"> 
        <div class="col-md-6 col-md-offset-3 bookingform"> 
            <h1>Stall Booking Form</h1> 
            <p class="lead"> Fill out the form to book and pay for your stall! </p> 
            <form id="bookingForm"> 
                <div class="form-group"> 
                    <label for="name">Name: </label> 
                    <input type="text" name="name" class="form-control" placeholder="Your Name" value="" title="Please enter your name" required/> 
                </div> 
                <div class="form-group"> 
                    <label for="address">Address: </label> 
                    <textarea name="address" class="form-control" placeholder="Your Address" value="" title="Please enter your address"></textarea> 
                </div> 
                <div class="form-group"> 
                    <label for="phone">Telephone Number: </label> 
                    <input type="text" name="phone" class="form-control" placeholder="Your Telephone Number" value="" title="Please enter the best telephone number to contact you on"/> 
                </div> 
                <div class="form-group"> 
                    <label for="email">Email: </label> 
                    <input type="text" name="email" class="form-control" placeholder="Your Email" value="" title="Please enter your Email address"/> 
                </div> 
                <div class="form-group"> 
                    <label for="date">Which date would you like to book?: </label> 
                    <p><input type="radio" name="date" value="13th September" /> Sunday 13th September</p> 
                    <p><input type="radio" name="date" value="6th February" /> Saturday 6th February</p> 
                </div> 
                <div class="form-group"> 
                    <label>What type of stall do you require?</label> 
                    <div> 
                        <input type="radio" name="stallType" id="stallType-Preloved" value="Preloved"> 
                        <label for="stallType-Preloved">Preloved</label> 
                        <div class="reveal-if-active"> 
                            <label for="c-rail">Will you be bringing a clothes rail?: </label> 
                            <input type="radio" name="c-rail" value="Yes" /> Yes 
                            <input type="radio" name="c-rail" value="No" /> No 
                        </div> 
                    </div> 
                    <div> 
                        <input type="radio" name="stallType" id="stallType-Craft" value="Craft"> 
                        <label for="stallType-Craft">Craft</label> 
                        <div class="reveal-if-active"> 
                            <label for="craftName">What name do you use?</label> 
                            <input type="text" id="craftName" name="craftName" class="require-if-active" placeholder="Craft Name" title="Please provide us with your Craft name" value="" /> 
                        </div> 
                    </div> 
                    <div> 
                        <input type="radio" name="stallType" id="stallType-Business" value="Business"> 
                        <label for="stallType-Business">Business</label> 
                        <div class="reveal-if-active"> 
                            <label for="bizName">What is your business name?</label> 
                            <input type="text" id="bizName" name="bizName" class="require-if-active" placeholder="Business Name" title="Please provide us with your Business name" value="" /> 
                            <label for="insurance">Do you have Public Liability Insurance?</label> 
                            <input type="radio" id="insurance" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="We will require proof of this prior to market day" value="Yes"/> Yes 
                            <input type="radio" id="insurance" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="Our insurance does not cover other businesses. Please ensure you have adequate cover and provide us with proof prior to market day" value="No"/> No 
                        </div> 
                    </div> 
                </div> 
                <input type="button" id="submit-form" class="btn btn-success btn-lg" value="Book & Pay" /> 
            </form> 
        </div> 
    </div> 
    <!-- /.row --> 
    <hr> 
    <!-- Footer --> 
    <footer> 
        <div class="row"> 
            <div class="col-lg-12"> 
                <p>Copyright &copy; MooWoos 2018. Website by Luke Brewerton</p> 
            </div> 
        </div> 
        <!-- /.row --> 
    </footer> 
</div> 
<!-- /.container --> 
<!--build:js js/mwbookings-min.js --> 
<script src="js/jquery.min.js"></script> 
<script src="js/tether.min.js"></script> 
<script src="js/bootstrap.min.js"></script> 
<script src="js/jquery.serialize-object.min.js"></script> 
<script src="js/main.js"></script> 
<!-- endbuild --> 
</body> 
</html>

我的JS文件代码:

var $form = $('form#bookingForm'), url = 'https://script.google.com/macros/s/AKfycbwaEsXX1iK8nNkkvL57WCYHJCtMAbXlfSpSn3rsJj2spRi-41Y/exec'
function validateForm() {
  var errorMessage="";
  var name=document.forms["bookingForm"]["name"].value;
  if (name==null ||name==""){
    errorMessage = "Your Name is required.\ ";
  }
  if (errorMessage !=""){
    alert(errorMessage);
    return false;
  }
}
$('#submit-form').on('click', function(e) {
  //e.preventDefault();
  var jqxhr = $.ajax({
    url: url,
    method: "GET",
    dataType: "json",
    data: $form.serializeObject(),
    success: function () {
      $('#redirect_page').modal('show');
      window.setTimeout(function(){location.reload()},3000);
    }
  });
});

解决方案

问题核心很简单:你写了validateForm()验证函数,但从来没有在提交按钮的点击事件里调用它,所以代码直接跳过验证执行AJAX了。另外,你的验证函数只检查了用户名,我帮你补充了其他必填字段的验证逻辑,让表单验证更完整。

修改后的JS代码如下:

var $form = $('form#bookingForm'), url = 'https://script.google.com/macros/s/AKfycbwaEsXX1iK8nNkkvL57WCYHJCtMAbXlfSpSn3rsJj2spRi-41Y/exec'

function validateForm() {
  var errorMessage = "";
  // 验证姓名必填
  var name = document.forms["bookingForm"]["name"].value;
  if (name == null || name === "") {
    errorMessage = "Your Name is required.";
  }
  // 验证邮箱格式
  var email = document.forms["bookingForm"]["email"].value;
  if (!email.match(/^\S+@\S+\.\S+$/)) {
    errorMessage += errorMessage ? "\n" : "";
    errorMessage += "Please enter a valid email address.";
  }
  // 验证是否选择了预订日期
  var dateSelected = document.querySelector('input[name="date"]:checked');
  if (!dateSelected) {
    errorMessage += errorMessage ? "\n" : "";
    errorMessage += "Please select a booking date.";
  }
  // 验证是否选择了摊位类型
  var stallTypeSelected = document.querySelector('input[name="stallType"]:checked');
  if (!stallTypeSelected) {
    errorMessage += errorMessage ? "\n" : "";
    errorMessage += "Please select a stall type.";
  }
  // 根据选中的摊位类型验证对应子字段
  if (stallTypeSelected) {
    if (stallTypeSelected.value === "Craft") {
      var craftName = document.forms["bookingForm"]["craftName"].value;
      if (craftName == null || craftName === "") {
        errorMessage += errorMessage ? "\n" : "";
        errorMessage += "Craft name is required.";
      }
    } else if (stallTypeSelected.value === "Business") {
      var bizName = document.forms["bookingForm"]["bizName"].value;
      if (bizName == null || bizName === "") {
        errorMessage += errorMessage ? "\n" : "";
        errorMessage += "Business name is required.";
      }
      var insuranceSelected = document.querySelector('input[name="insurance"]:checked');
      if (!insuranceSelected) {
        errorMessage += errorMessage ? "\n" : "";
        errorMessage += "Please select if you have public liability insurance.";
      }
    }
  }

  // 如果有错误提示,弹出并返回验证失败
  if (errorMessage !== "") {
    alert(errorMessage);
    return false;
  }
  // 验证通过返回true
  return true;
}

$('#submit-form').on('click', function(e) {
  // 先执行验证,验证失败直接返回,不执行AJAX
  if (!validateForm()) {
    return;
  }
  // 验证通过后发起AJAX请求
  var jqxhr = $.ajax({
    url: url,
    method: "GET",
    dataType: "json",
    data: $form.serializeObject(),
    success: function () {
      $('#redirect_page').modal('show');
      window.setTimeout(function(){location.reload()},3000);
    }
  });
});

关键修改点:

  1. 在点击事件中调用验证函数:点击提交按钮时,先执行validateForm(),如果返回false(验证失败),就直接终止后续代码,不发起AJAX请求
  2. 完善验证逻辑:补充了邮箱格式、日期选择、摊位类型选择,以及不同摊位类型对应的子字段验证,让表单更严谨
  3. 验证函数返回状态:确保验证通过时返回true,这样才会执行后续的AJAX代码

如果你想结合HTML5原生的required属性验证,可以在验证函数开头加上:

// 检查HTML5原生验证规则是否通过
if (!$form[0].checkValidity()) {
  // 触发原生验证提示
  $form[0].reportValidity();
  return false;
}

这样能同时利用原生验证和自定义验证逻辑,体验更好。

内容的提问来源于stack exchange,提问作者Luke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:21:15