Most error checking programs check each field one at a time, and display one error at a time. This can make filling out the form tedious, and people might stop in the middle. If you use the following script and Perl source you will know how to validate an entire form at once, displaying a series of error messages that your reader can then go back and fix.
In the head portion of your HTML, you should create a script to do the form validation:
<!-- // ignore if non-JS browser
- This is the function call that starts the validation. It's good form to set your variables at the top of your script.
var error = "";
- If you have drop-down elements in your forms, you should include the first option as an empty field (e.g.
<option value="">choose one</option>) You can include any text you would like on the field, as long as the value is blank. Then, when you validate against it, simply look to see if the first option (the blank one) is still set, if it is, write the error message.
if (theForm.dd.options.selected == true)
error += "Please select from the drop-down list.\n";
- Text elements are the easiest to validate. Simply check to see if the value is empty. If it is, set the error message.
if (theForm.words.value == "")
error += "Please fill in the text element.\n";
- If you want to validate the type of data within a text field, you have to get a bit fancier. This snippet of script looks at a text box to see if it has non-numerical characters in it (the variable "digits" defines what it is looking for).
var digits = "0123456789";
if (theForm.number.value == "")
error += "Please fill in a number.\n";
for (var i = 0; i < theForm.number.value.length; i++)
temp = theForm.number.value.substring(i, i+1)
if (digits.indexOf(temp) == -1 && theForm.number.value != "")
error += "The numerical text must be a number.\n";
This article is part of the HTML Forms Tutorial