使用AJAX调用忽略Forn Validation

时间:2018-01-23 11:19:41

标签: javascript jquery ajax forms

我有一个使用AJAX调用的表单将信息提交给Google表格,除非我尝试添加表单验证时工作正常。然后它只是运行AJAX调用。

以下是我的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 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);
        }
    });
});

我有一种偷偷摸摸的感觉,我需要在AJAX调用之前在提交函数中进行表单验证,但我不熟悉使用JS来执行此操作,之前我已经使用PHP来完成所有操作。

2 个答案:

答案 0 :(得分:1)

主要问题是您没有在任何地方调用validateForm()函数。您需要在提交表单之前调用它以检查其有效性。

出于辅助功能的原因,您还应该在表单中使用type="submit"按钮。这也将允许用户在字段处于焦点时通过按返回键来提交表单。然后,您可以挂钩submit事件来处理表单提交。试试这个:

<form id="bookingForm">
  <!-- form fields... -->

  <input type="submit" id="submit-form" class="btn btn-success btn-lg" value="Book & Pay" />
</form>
function validateForm() {
  var errorMessage = "";
  var name = $('input[name="name"]').val();
  if (name == null || name == "") {
    errorMessage = "Your Name is required.\n";
  }
  return errorMessage;
}

$form.on('submit', function(e) {
  e.preventDefault();

  var error = validateForm();
  if (error) {
    alert(error);
    return;
  }

  var jqxhr = $.ajax({
    // ajax request...
  });
});

但是请注意,在大多数浏览器中,required属性将为您实现此逻辑,而无需任何JS干预。

答案 1 :(得分:0)

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.\
    ";
return true;
}

if (errorMessage !=""){
    alert(errorMessage);
    return false;
}
}

$('#submit-form').on('click', function(e) {
//e.preventDefault();

var res = validateForm();
if(res != false) {

var jqxhr = $.ajax({
    url: url,
    method: "GET",
    dataType: "json",
    data: $form.serializeObject(),
    success: function () {
        $('#redirect_page').modal('show');
        window.setTimeout(function(){location.reload()},3000);
    }
});
} else {
//handle else condition however u want
}
});