...

View Full Version : Stopping submit if form invalid



Iceman Luch
12-24-2010, 01:19 AM
I wrote a form and a JavaScript to valid the form. I cannot figure out however how to stop the form from submitting if the form is invalid.

[CODE]
function validateForm()
{

if(""==document.test.custName.value)
{
alert("Please enter your name.");
return false;
}

if(""==document.test.email.value)
{
alert("Please enter your email address.");
return false;
}

if(""==document.test.custComment.value)
{
alert("Please enter your comment.");
return false;
}

return true;
}
[CODE]

DJCMBear
12-24-2010, 02:10 AM
Try putting the if's the other way around.


if(document.test.custComment.value === "")

EXAMPLE:



function validateForm() {
var e=false,w=[];
if(document.test.custName.value === '') {
w[0] = "Please enter your name.";
e = true;
}
if(document.test.email.value === '') {
w[1] = "Please enter your email address.";
e = true;
}
if(document.test.custComment.value === '') {
w[2] = "Please enter your comment.";
e = true;
}
if(e) {
alert(w.join("\n"));
return false;
}
}


EDIT:
Are you using the function in a button onclick action or the form onsubmit action?

jmrker
12-24-2010, 04:00 AM
I wrote a form and a JavaScript to valid the form. I cannot figure out however how to stop the form from submitting if the form is invalid.



function validateForm() {
if(""==document.test.custName.value) {
alert("Please enter your name.");
return false;
}
if(""==document.test.email.value) {
alert("Please enter your email address.");
return false;
}
if(""==document.test.custComment.value) {
alert("Please enter your comment.");
return false;
}
return true;
}


If using <form> tag:


<form name="my_form" action='' onsubmit="return validateForm">



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum