Simple Contact Form With JavaScript Validation
This is a very simple contact form script with JavaScript validation.
This form has three fields name, email address and message but can be easily modified with new fields.
Here is an example of the contact form
I hope to see some examples of what you do with this script. Like Mark Ireland has done with my previous Simple JavaScript Calculator script.
<!-- This function is called to validate a field in a form, when the function is called the field that needs to be validated and the text to display if the field is not valid is specified -->
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false}
else {return true}
}
}
<!-- This function is called to validate the value entered into the email fieldof the table, when the function is called the field that needs to be validated and the text to display if the field is not valid is specified -->
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@")
dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false}
else {return true}
}
<!-- This function is called when the form is submitted, it goes through and calls different functions to validate different field types, when calling the function it specifies the field to be validated and the text to display if the field is not valid -->
}function validate_form(thisform)
{
with (thisform)
{
if (validate_required(name,"Please enter your name!")==false)
{name.focus();return false}
if (validate_email(email,"Not a valid e-mail address!")==false)
{email.focus();return false}
if (validate_required(message,"Please enter a message!")==false)
{message.focus();return false}
}
}
</script>
<!-- when the form is submitted it calls the function validate_form to validate the form before it is posted. -->
<form name="contact" action="http://www.sam-i-am.com/cgi-bin/echoform.cgi" method="post" onSubmit="return validate_form(this);">
<table border="0">
<tr>
<td colspan="2" id="counttitle">Contact Us</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="2"><table border="0" cellpadding="0" cellspacing="1" bgcolor="#000000">
<tr>
<td width="150" bgcolor="#FFFFFF">Name:</td>
<td bgcolor="#FFFFFF"><input type="text" name="name" size="30" maxlength="30" value=""></td>
</tr>
<tr>
<td bgcolor="#FFFFFF">Email Address:</td>
<td bgcolor="#FFFFFF"><input type="text" name="email" size="30" maxlength="30" value="" id="email"></td>
</tr>
<tr>
<td valign="top" bgcolor="#FFFFFF">Message:</td>
<td width="400" bgcolor="#FFFFFF"><textarea name="message" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<td bgcolor="#FFFFFF"> </td>
<td bgcolor="#FFFFFF"><input type="submit" name="submit" value="Send"></td>
</tr>
</table></td>
</tr>
</table>
</form>
Have Fun
