Form Validation
Form validation is a way to "interrupt" the pressing of the submit button and send the processing off to the javascript function specified. If this function returns "true" the regular submit process continues. If this function returns "false" then the form is not submitted and the current page stays in place. So it is very important that you give the user some message, either written directly on the page or as an alert, if the form is not being submitted.
In a very simple form you may just want to check for Name and Email address. If more fields are required, you should check that the values are in "normal" range so the user doesn't mistakenly send you bad information.
Modify the Form to call the function
Capture the submission just as the user presses Submit:
<form id="form1" name="form1" method="post"
onsubmit="return validateForm(this)"
action="/cgi-bin/form-mail/~webclass/raneym3/forms/form.cfg" >
Modify the Form to specify what's required
One way is to add a "required" class to each field you want to process. Alternatively you could process all the text fields or just plan to validate every element.
Name:
<input name="name" type="text" id="name" size="24" maxlength="24" class="required"/>
Email:
<input name="email" type="text" id="email" size="32" maxlength="32" class="email required"/>
Write the Validation Function
<script type="text/javascript">
//check that there's at least one character in the
//field and that the default value is not still in the field
function isFilled(field) {
if (field.value.length < 1 || field.value == field.defaultValue) {
return false;
} else {
return true;
}
}
// check for presence of a "@" and a "."
// - if they're present it's good enough
function isEmail(field){
if (field.value.indexOf("@") == -1 ||
field.value.indexOf(".") == -1){
return false;
} else {
return true;
}
}
// check that required fields are filled
// and that email is valid
function validateForm(whichform){
for (var i=0; i<whichform.elements.length; i++) {
var element = whichform.elements[i];
if (element.className.indexOf("required") != -1) {
//is required, so validate
if (!isFilled(element)){
alert("Please fill in the "+element.name+" field.");
return false;
}
}//end class required
if (element.className.indexOf("email") != -1){
// email is required, so validate
if (!isEmail(element)){
alert ("The " +element.name+
" field must be a valid email address.");
return false;
}
}//end email
}//end for
return true;
} //end function
</script>
To see modifications for adding anti-spam logic, please see these updates
