我写过一个函数,除非有两个条件成立,否则应该阻止提交任何内容 - 即已将值放入每个必需的类别中,如果每个类别都有值,则表示有效的电话号码有已经提交。
相反,现在发生的事情是我会收到错误消息,但无论如何它都会提交表单。我没有在代码中看到错误,你能看到什么吗?
function formValidation() {
var ids = ["orgname", "cultpicklist", "catpicklist", "servpicklist", "phone", "add1", "url", "state"] // required fields
formValue = 1; // value indicating whether to go to the next step of the process, phone number validation. On by default.
if (document.getElementById('deletebutton') != null && document.getElementById('orgname').value === "") {
formValue = 0; // A separate test for when the delete button is clicked.
}
else {
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0; // Testing each of the list items
break;
}
}
}
// Here's the part where, if everything else passes checks, we have a regex test for phone number validation
if (formValue == 1) {
phoneVal = document.getElementById("phone");
if (/^\d{3}-\d{3}-\d{4}$/.test(phoneVal) || /^\d{10}$/.test(phoneVal) || /^\(\d{3}\) \d{3}-\d{4}$/.test(phoneVal)) {
return true;
}
else {
alert("Please put in a correct phone number");
return false;
// This shouldn't submit, but does.
}}
else if (formValue == 0) {
alert('Please fill out all required fields');
return false;
// This also shouldn't submit, but does as well.
}
}
答案 0 :(得分:1)
我假设你的html中有这样的东西
<form .... onsubmit="formValidation()">
应该是
<form .... onsubmit="return formValidation()">
答案 1 :(得分:0)
是否从提交按钮调用此函数?
提交按钮将提交表单,无论javascript告诉它做什么。考虑使用普通旧按钮并使用表单的submit()函数。
http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="form" action="no.html">
<input type="button" value="submit" onmousedown="dontSub()" />
</form>
</body>
<script>
function dontSub() {
var good = false;
if(good) {
document.forms["form"].submit();
}
}
</script>
</html>