Javascript Form Validation?
Is anybody out there good with javascript? I need to set up a simple form validation on my contact form, and for whatever reason, I can’t get it to work properly. I just want it to check to make sure that 4 out of the 5 form fields have a value entered, and if they don’t then show an alert box with the names of missing fields. If anybody could point me towards (or write me) a simple script that will do this (and only this, I don’t need anything else fancy), I’d be very grateful. Let me know either here in the comments, or drop me an email.
PS. I think my comments can accept coding examples as long as you wrap them in a < code > tag (minus the spaces).
- I only get it for the articles
- The Impersonals - get it? The “IM-personals”? Get it? GET IT????
- Hosting & Boasting
- All the news that’s unfit to print!
- Disabling right mouse click
- Prev: The Buddhist Monk-Dog
- Next: Medieval Clip Art




![[tmbchr]™](/journal/popocculture-blog-logo.jpg)
September 18th, 2005 at 9:50 pm
Something like this seems to work for me:
<SCRIPT TYPE="text/javascript">
function validate_form ( )
{
error = false;
error_string = "Please fill in these field(s):";
if ( document.contact.name.value == "" )
{
error = true;
error_string = error_string + " name";
}
if ( document.contact.email.value == "" )
{
error = true;
error_string = error_string + " email";
}
if ( document.contact.subject.value == "" )
{
error = true;
error_string = error_string + " subject";
}
if ( document.contact.comments.value == "" )
{
error = true;
error_string = error_string + " comments";
}
if (error == true)
{
alert (error_string);
}
return (!error);
}
</SCRIPT>
and don’t forget to change the form tag to include an onsubmit:
<form action="formmail.php" method="post" name="contact" id="contact" onsubmit="return validate_form()">
September 18th, 2005 at 11:43 pm
function checkForm()
{
flag = "off"
msg = "Please fill in the following missing fields:"
formObj = document.forms[0]
numFields = formObj.length - 1
for(i=0; i< numFields;i++)
{
if(formObj.elements[i].value == "")
{
if (formObj.elements[i].name != "website")
{
msg = msg + "\n - " + formObj.elements[i].name
flag = "on"
}
}
}
if (flag == "on")
{
alert(msg)
return false;
}
}
September 18th, 2005 at 11:45 pm
Oops… forgot that tag you mentioned above
And as Davee said… don’t forget to amend the form tag to include an onSubmit()
September 18th, 2005 at 11:48 pm
AHHH… that did the trick. Much much simpler than the stuff I was trying to do. I really need to brush up on this stuff.
Thank you very much!
September 18th, 2005 at 11:49 pm
ooh, wait, i only saw davee’s. let me try mikes. I love that little array action.
September 19th, 2005 at 12:03 am
PS. If anybody’s having trouble posting code, don’t worry about it. I’ve got this all figured out.
But just FYI, it seems that the Wordpress commenting system filters out the script tag unless you replace the angle brackets with their & lt; style equivalents