Javascript表单验证+ ajax提交无效

时间:2017-06-25 13:46:46

标签: javascript jquery ajax forms validation

我使用Javascript来验证表单。如果验证脚本在表单中没有找到错误,那么应该运行ajax提交代码,但它不是。我不确定为什么。如果我将提交代码放入自己的脚本并删除验证,表单提交就好了。我还应该注意,如果在console.log("Success")之前和之后放置$("#foo").submit(function(event) {,则只能看到第一个控制台日志。所以似乎提交函数由于某种原因不会被触发。

<form id="foo" method="post" name="nomForm" action="nominate-test.html#thankyou" onsubmit="return validateForm()">

  <div class="page1">
    <label class="row">
      <h2 class="headline">Your name</h2>
      <input placeholder="e.g. John Smith" type="text" name="name" id="name" tabindex="1" autofocus>
      <span id="nameError" class="error headline"></span>
    </label>

    <label class="row email">
      <h2 class="headline">Your email address</h2>
      <input placeholder="example@rofordaward.co.uk" type="text" name="email" id="email" tabindex="2">
      <span id="emailError" class="error headline"></span>
    </label>

    <label class="row">
      <h2 class="headline">Company name</h2>
      <input placeholder="e.g. Roford" type="text" name="company" id="company" tabindex="3">
      <span id="companyError" class="error headline"></span>
    </label>
    <div class="next">
      <button type="button" id="moveup">Next page</button><i class="icon-down-open"></i></div>
  </div>

  <div class="page2">
    <label class="row reason">
      <h2 class="headline">Reason for nomination</h2>
      <textarea id="textarea" rows="6" cols="25" maxlength="1000" name="message" id="message" placeholder="A brief evidence based summary"></textarea>
      <span id="messageError" class="error headline"></span>
      <div id="text-area-wrap">
        <div id="textarea_feedback"></div>
      </div>
    </label>

    <div class="row button-wrap">
      <div class="column small-12">
        <input class="button" name="submit" type="submit" id="contact-submit" value="Submit">
      </div>
    </div>
    <div class="prev">
      <button type="button" id="movedown">Previous page</button><i class="icon-up-open"></i></div>
  </div>

</form>


function validateForm() {
  var name = document.nomForm.name.value;
  var email = document.nomForm.email.value;
  var company = document.nomForm.company.value;
  var message = document.nomForm.message.value;
  var errorCount = 0;

  if (name == "") {
    document.getElementById('nameError').innerHTML = "Please enter your name";
    errorCount++;
  } else {
    var specCharNum = "~`!#$%^&*+=[]\\\';,/{}|\":<>?1234567890";
    for (var i = 0; i < name.length; i++) {
      if (specCharNum.indexOf(name.charAt(i)) != -1) {
        document.getElementById('nameError').innerHTML = "Please enter a valid name";
        errorCount++;
      }
    }
  }

  if (email == "") {
    document.getElementById('emailError').innerHTML = "Please enter your email address";
    errorCount++;
  } else {
    var atpos = email.indexOf("@");
    var dotpos = email.lastIndexOf(".");

    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 > email.length) {
      document.getElementById('emailError').innerHTML = "Please enter a valid email address";
      errorCount++;
    }
  }

  if (company == "") {
    document.getElementById('companyError').innerHTML = "Please enter a company name";
    errorCount++;
  } else {
    var specChar = "~`!#$%^&*+=[]\\\';,/{}|\":<>?";
    for (var i = 0; i < name.length; i++) {
      if (specChar.indexOf(name.charAt(i)) != -1) {
        document.getElementById('companyError').innerHTML = "Please enter a valid company name";
        errorCount++;
      }
    }
  }

  if (message == "") {
    document.getElementById('messageError').innerHTML = "Please enter a reason";
    errorCount++;
  } else {
    if (message.length > 1000) {
      document.getElementById('messageError').innerHTML = "You have exceeded the character limit";
      errorCount++;
    }
  }

  if (errorCount > 0) {
    return false;
  } else {
    // Variable to hold request
    var request;

    // Bind to the submit event of our form
    $("#foo").submit(function(event) {

      // Abort any pending request
      if (request) {
        request.abort();
      }
      // setup some local variables
      var $form = $(this);

      // Let's select and cache all the fields
      var $inputs = $form.find("input, select, button, textarea");

      // Serialize the data in the form
      var serializedData = $form.serialize();

      // Let's disable the inputs for the duration of the Ajax request.
      // Elements are disabled AFTER the form data has been serialized.
      // Disabled form elements will not be serialized.
      $inputs.prop("disabled", true);

      // Fire off the request to /form.php
      request = $.ajax({
        url: "https://script.google.com/macros/s/AKfycbwpTdztz-kSw8Ld1o0yly6BD-2cvJglpq2gkKioMjGoWDMO_HE/exec",
        type: "post",
        data: serializedData
      });

      // Callback handler that will be called on success
      request.done(function(response, textStatus, jqXHR) {
        // Log a message to the console
        console.log("Hooray, it worked!");
        console.log(response);
        console.log(textStatus);
        console.log(jqXHR);
      });

      // Callback handler that will be called on failure
      request.fail(function(jqXHR, textStatus, errorThrown) {
        // Log the error to the console
        console.error(
          "The following error occurred: " +
          textStatus, errorThrown
        );
      });

      // Callback handler that will be called regardless
      // if the request failed or succeeded
      request.always(function() {
        // Reenable the inputs
        $inputs.prop("disabled", false);
      });

      // Prevent default posting of form
      event.preventDefault();
    });
    return true;
  }
}

1 个答案:

答案 0 :(得分:1)

首先从表单中删除onsubmit事件,如下所示:

<form id="foo" method="post" name="nomForm" action="nominate-test.html#thankyou">

使用以下javascript代码:

function validateForm() {
  var name = document.nomForm.name.value;
  var email = document.nomForm.email.value;
  var company = document.nomForm.company.value;
  var message = document.nomForm.message.value;
  var errorCount = 0;

  if (name == "") {
    document.getElementById('nameError').innerHTML = "Please enter your name";
    errorCount++;
  } else {
    var specCharNum = "~`!#$%^&*+=[]\\\';,/{}|\":<>?1234567890";
    for (var i = 0; i < name.length; i++) {
      if (specCharNum.indexOf(name.charAt(i)) != -1) {
        document.getElementById('nameError').innerHTML = "Please enter a valid name";
        errorCount++;
      }
    }
  }

  if (email == "") {
    document.getElementById('emailError').innerHTML = "Please enter your email address";
    errorCount++;
  } else {
    var atpos = email.indexOf("@");
    var dotpos = email.lastIndexOf(".");

    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 > email.length) {
      document.getElementById('emailError').innerHTML = "Please enter a valid email address";
      errorCount++;
    }
  }

  if (company == "") {
    document.getElementById('companyError').innerHTML = "Please enter a company name";
    errorCount++;
  } else {
    var specChar = "~`!#$%^&*+=[]\\\';,/{}|\":<>?";
    for (var i = 0; i < name.length; i++) {
      if (specChar.indexOf(name.charAt(i)) != -1) {
        document.getElementById('companyError').innerHTML = "Please enter a valid company name";
        errorCount++;
      }
    }
  }

  if (message == "") {
    document.getElementById('messageError').innerHTML = "Please enter a reason";
    errorCount++;
  } else {
    if (message.length > 1000) {
      document.getElementById('messageError').innerHTML = "You have exceeded the character limit";
      errorCount++;
    }
  }

  return errorCount;
}

$("#foo").submit(function(event) {

  var request;

  if ( validateForm() !== 0 ) {
    return false;
  }

  // Abort any pending request
  if (request) {
    request.abort();
  }
  // setup some local variables
  var $form = $(this);

  // Let's select and cache all the fields
  var $inputs = $form.find("input, select, button, textarea");

  // Serialize the data in the form
  var serializedData = $form.serialize();

  // Let's disable the inputs for the duration of the Ajax request.
  // Elements are disabled AFTER the form data has been serialized.
  // Disabled form elements will not be serialized.
  $inputs.prop("disabled", true);

  // Fire off the request to /form.php
  request = $.ajax({
    url: "https://script.google.com/macros/s/AKfycbwpTdztz-kSw8Ld1o0yly6BD-2cvJglpq2gkKioMjGoWDMO_HE/exec",
    type: "post",
    data: serializedData
  });

  // Callback handler that will be called on success
  request.done(function(response, textStatus, jqXHR) {
    // Log a message to the console
    console.log("Hooray, it worked!");
    console.log(response);
    console.log(textStatus);
    console.log(jqXHR);
    window.location = "nominate-test.html#thankyou";
  });

  // Callback handler that will be called on failure
  request.fail(function(jqXHR, textStatus, errorThrown) {
    // Log the error to the console
    console.error(
      "The following error occurred: " +
      textStatus, errorThrown
    );
  });

  // Callback handler that will be called regardless
  // if the request failed or succeeded
  request.always(function() {
    // Reenable the inputs
    $inputs.prop("disabled", false);
  });

  // Prevent default posting of form
  event.preventDefault();
});

它阻止重新加载页面,然后执行你的ajax代码。运行ajax后,用javascript重定向用户感谢页面。