Javascript表单验证&x2B;ajax提交不起作用

Javascript表单验证&x2B;ajax提交不起作用,javascript,jquery,ajax,forms,validation,Javascript,Jquery,Ajax,Forms,Validation,我正在使用Javascript验证表单。如果验证脚本没有在表单中找到错误,那么ajax提交代码应该运行,但事实并非如此。我不知道为什么。如果我将提交代码放入自己的脚本中并删除验证,那么表单就可以提交了。我还应该注意,如果在$(“#foo”).submit(函数(事件){)之前和之后放置console.log(“Success”),则只能看到第一个控制台日志。因此,出于某种原因,提交函数似乎没有启动 <form id="foo" method="post" name="nomForm" ac

我正在使用Javascript验证表单。如果验证脚本没有在表单中找到错误,那么ajax提交代码应该运行,但事实并非如此。我不知道为什么。如果我将提交代码放入自己的脚本中并删除验证,那么表单就可以提交了。我还应该注意,如果在
$(“#foo”).submit(函数(事件){
)之前和之后放置
console.log(“Success”)
,则只能看到第一个控制台日志。因此,出于某种原因,提交函数似乎没有启动

<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>

你的名字
你的电子邮件地址
公司名称
下一页
提名理由
上一页

函数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;
如果(名称==“”){
document.getElementById('nameError').innerHTML=“请输入您的姓名”;
errorCount++;
}否则{
var specCharNum=“~`!\\$%^&*+=[]\\\\',/{}\\\\”:?1234567890”;
对于(变量i=0;iemail.length){
document.getElementById('emailError').innerHTML=“请输入有效的电子邮件地址”;
errorCount++;
}
}
如果(公司==“”){
document.getElementById('companyError').innerHTML=“请输入公司名称”;
errorCount++;
}否则{
var specChar=“~`!\\$%^&*+=[]\\\”,/{}\\\\”:;
对于(变量i=0;i1000){
document.getElementById('messageError').innerHTML=“您已超过字符限制”;
errorCount++;
}
}
如果(错误计数>0){
返回false;
}否则{
//保存请求的变量
var请求;
//绑定到表单的提交事件
$(“#foo”).submit(函数(事件){
//中止任何挂起的请求
如果(请求){
request.abort();
}
//设置一些局部变量
var$form=$(此);
//让我们选择并缓存所有字段
var$inputs=$form.find(“输入、选择、按钮、文本区域”);
//序列化表单中的数据
var serializedData=$form.serialize();
//让我们在Ajax请求期间禁用输入。
//表单数据序列化后,将禁用元素。
//禁用的表单元素将不会序列化。
$inputs.prop(“禁用”,真);
//向/form.php发出请求
请求=$.ajax({
url:“https://script.google.com/macros/s/AKfycbwpTdztz-kSw8Ld1o0yly6BD-2cvJglpq2gkKioMjGoWDMO_HE/exec",
类型:“post”,
数据:序列化数据
});
//成功时将调用的回调处理程序
完成(函数(响应、文本状态、jqXHR){
//将消息记录到控制台
log(“万岁,成功了!”);
控制台日志(响应);
console.log(textStatus);
console.log(jqXHR);
});
//失败时将调用的回调处理程序
失败(函数(jqXHR、textStatus、errorshown){
//将错误记录到控制台
控制台错误(
“发生了以下错误:”+
文本状态,错误抛出
);
});
//将被调用的回调处理程序
//如果请求失败或成功
request.always(函数(){
//重新启用输入
$inputs.prop(“禁用”,false);
});
//防止表单的默认过帐
event.preventDefault();
});
返回true;
}
}

首先从表单中删除
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();
});
函数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;
如果(名称==“”){
document.getElementById('nameError').innerHTML=“请输入您的姓名”;
errorCount++;
}否则{
var specCharNum=“~`!\\$%^&*+=[]\\\\',/{}\\\\”:?1234567890”;
对于(变量i=0;iemail.length){
document.getElementById('emailError').innerHTML=“请输入有效的电子邮件地址”;
errorCount++;
}
}
如果(公司==“”){
document.getElementById('companyError').innerHTML=“请输入公司名称”;
errorCount++;
}否则{
var specChar=“~`!\\$%^&*+=[]\\\”,/{}\\\\”:;
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();
});