Form Validation
One of the primary reasons JavaScript was assembled was to check whether the values entered into forms by readers were correct, thereby bypassing the lengthy trip to a CGI program to do the check. Here we'll learn the methods used to validate form input, using the onSubmit
event handler.
This page was last updated on 2012-08-21
Validating Form Input
When you submit a form to a CGI program that resides on the server, it is usually programmed to do its own check for errors. If it finds any it sends the page back to the reader who then has to re-enter some data, before submitting again. A JavaScript check is useful because it stops the form from being submitted if there is a problem, saving lots of time for your readers.
The CGI script is still more reliable, as it always works regardless of whether JavaScript is enabled on the client-side or not; but having this extra safety barrier is a nice thing to have in place. It makes your page much more user-friendly, and takes out the frustration of having to fill out the same form repeatedly. It's also very precise, as you can point out the exact field where there's a problem.
Implementing the Check
We're going to be checking the form using a function, which will be activated by the form's submit
event — therefore, using the onSubmit
handler. Add an attribute like this to the form you wish to validate:
<form action="script.cgi" onSubmit="return checkform()">
Where checkForm
is the name of the function we're about to create. If you've learnt your functions properly, you should be able to guess that our function will return
a Boolean value — either true
or false
. Submit
's default action is to submit the data, but if you give onSubmit
a value of return false
, it will not be submitted; just like how we can stop a link from being followed. Of course, if there are no problems, the function call will be replaced by true
and the data will be submitted. Simple...
It's impossible for me to give you a definitive validation script, as every form is different, with a different structure and different values to check for. That said, it is possible to give you the basic layout of a script, which you can then customise to the needs of your form.
A general script looks like this:
function checkform() { if (value of first field is or isn't something) { // something is wrong alert('There is a problem with the first field'); return false; } else if (value of next field is or isn't something) { // something else is wrong alert('There is a problem with...'); return false; } // If the script gets this far through all of your fields // without problems, it's ok and you can submit the form return true; }
If your form is quite complex your script will grow proportionally longer too, but the fundamentals will stay the same in every instance — you go through each field with if
and else
statements, checking the inputted values to make sure they're not blank. As each field passes the test your script moves down to the next.
If there is a problem with a field, the script will return false
at that point and stop working, never reaching the final return true
command unless there are no problems at all. You should of course tailor the error messages to point out which field has the problem, and maybe offering solutions to common mistakes.
Accessing Values
Having read the Objects and Properties page, you should now know how to find out the values of form elements through the DOM. We're going to be using the name
notation instead of using numbered indexes to access the elements, so that you are free to move around the fields on your page without having to rewrite parts of your script every time. A sample, and simple, form may look like this:
<form name="feedback" action="script.cgi" method="post" onSubmit="return checkform()">
<input type="text" name="name">
<input type="text" name="email">
<textarea name="comments"></textarea>
</form>
Validating this form would be considerably simpler than one containing radio buttons or select boxes, but any form element can be accessed. Below are the ways to get the value from all types of form elements. In all cases, the form is called feedback
and the element is called field
.
Text Boxes, <textarea>s and hiddens
These are the easiest elements to access. The code is simply
document.feedback.field.value
You'll usually be checking if this value is empty, i.e.
if (document.feedback.field.value == '') { return false; }
That's checking the value's equality with a null String (two single quotes with nothing between them). When you are asking a reader for their email address, you can use a simple » address validation function to make sure the address has a valid structure.
Select Boxes
Select boxes are a little trickier. Each option in a drop-down box is indexed in the array options[]
, starting as always with 0. You then get the value of the element at this index. It's like this:
document.feedback.field.options [document.feedback.field.selectedIndex].value
You can also change the selected index through JavaScript. To set it to the first option, execute this:
document.feedback.field.selectedIndex = 0;
Check Boxes
Checkboxes behave differently to other elements — their value is always on
. Instead, you have to check if their Boolean checked
value is true or, in this case, false.
if (!document.feedback.field.checked) { // box is not checked return false; }
Naturally, to check a box, do this
document.feedback.field.checked = true;
Radio Buttons
Annoyingly, there is no simple way to check which radio button out of a group is selected — you have to check through each element, linked with Boolean AND operators . Usually you'll just want to check if none of them have been selected, as in this example:
if (!document.feedback.field[0].checked && !document.feedback.field[1].checked && !document.feedback.field[2].checked) { // no radio button is selected return false; }
You can check a radio button in the same way as a checkbox.