Reputation: 11305
I've written a function which SHOULD prevent anything from being submitted unless two conditions are true - namely that values have been put into each of the required categories, and if there are values in every category, that a valid phone number has been submitted.
Instead, what is happening right now is I'll get the error message, but then it will submit the form anyway. I'm not seeing the error in my code, can you see anything?
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.
}
}
Upvotes: 0
Views: 46
Reputation: 6124
Is this function called from the submit button?
submit buttons will submit the form regardless of what the javascript tells it to do. Consider using a plain old button and using the form's submit() function.
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>
Upvotes: 0
Reputation: 196112
I am assuming that in your html you have something like this
<form .... onsubmit="formValidation()">
It should be
<form .... onsubmit="return formValidation()">
Upvotes: 1