如何在验证失败后停止提交表单。

时间:2016-12-10 19:59:01

标签: javascript forms validation

我一直在研究这个表格并且遇到了障碍。如果验证失败,我试图阻止表单提交。表单本身使用formspree.io来收集结果并通过电子邮件发送给他们。我打算在所有的js中写这个。

我认为因为这个添加返回false到任何验证结束都不起作用,因为formspree正在做一些我不知道/不理解的额外事情。

这是我的代码,没有表单元素,只有验证逻辑和提交按钮。您可以查看表单here的所有代码。感谢任何帮助或提示或指示。

var app = document.createElement('form');
app.name = 'formIT'
app.action = "https://formspree.io/alaw989@gmail.com"
app.method = "POST"

//all div elements and stuff used to build the form would be here//

var submit = document.createElement('button'); 
submit.textContent = 'Submit'
app.appendChild(submit)
submit.style.cssText = "display: block; margin: 40px 0px 0px 20px; background-color: #1DA2F5; border: none; color: white; padding: 16px 32px; text-decoration: none; cursor: pointer;"
submit.type = "submit"
submit.value = "Send"

submit.addEventListener('click', function() {
   var x = emailInput.value;
   var atpos = x.indexOf("@");
   var dotpos = x.lastIndexOf(".");
     if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        alert("Not a valid e-mail address");
    }

  var yes1 = radio1a.checked;
  var no1 = radio1b.checked;

  if (yes1 == "" && no1 == "") {
    alert("Please answer question 1")
  }

  var yes2 = radio2a.checked;
  var no2 = radio2b.checked;

  if (yes2 == "" && no2 == "") {
    alert("Please answer question 2")    
  }

  var yes3 = radio3a.checked;
  var no3 = radio3b.checked;

  if (yes3 == "" && no3 == "") {
    alert("Please answer question 3")    
  }

  var yes4 = radio4a.checked;
  var no4 = radio4b.checked;

  if (yes4 == "" && no4 == "") {
    alert("Please answer question 4")    
  }

  var yes5 = radio5a.checked;
  var no5 = radio5b.checked;

  if (yes5 == "" && no5 == "") {
    alert("Please answer question 5")    
  }

  var yes6 = radio6a.checked;
  var no6 = radio6b.checked;

  if (yes6 == "" && no6 == "") {
    alert("Please answer question 6")    
  }

   var a = input1.value
   var b = input2.value
   if (a === "") {
    alert("Missing Question 7")
   }
   if (b === "") {
     alert("Missing Question 8")
   }

});

3 个答案:

答案 0 :(得分:0)

对于你的问题,我建议使用一个错误捕捉功能或类似功能,这会在错误时杀死脚本。

查看答案:Is it possible to stop JavaScript execution?

答案 1 :(得分:0)

尝试

app.get('/', function (req, res) {
   customers =  fs.readFile('./testData.json', 'utf8', function(err, data) {
        if(err) {
            return console.log(err);
        }
        res.send(data);
    });
});

答案 2 :(得分:0)

首先,您的单选按钮“已选中”事件应该检查​​是否为“”而不是“”。其次,您有两种选择。你可以在你的点击事件中添加e,并按照Matias的建议添加e.preventDefault():

submit.addEventListener('click', function(e) {
    e.preventDefault();
}

或者在表单标记中添加一个验证表单的函数:

<form onsubmit="validateForm();">