Many, many web sites have forms built into web pages where they're used for such things as:
- entering details for new user accounts
- log on details
- emails
- on-line chat
- uploading and downloading data
With all that data someone, somewhere, is going to make a mistake - and that's where form validation can help.
Form validation can occur in one of two places:
- on the client - before the data has been sent
- on the server - after the data has been sent
This article will look at how to validate a form on the client - by using Javascript.
A Simple HTML Form
Obviously a form is needed before any validation can take place - in this example the form will contain:
- input boxes for text and numbers
- radio buttons
- a drop-down (or combo) box
- a button to submit the form
There are two important things to note in the above form:
- the form must be named (in this case it's called userdata)
- instead of using a submit button the form has a button to call a Javascript function - this function will validate the form and then sent the data to the target specified by the form's action property
The next step is to write the functions that will carry out the form validation.
The First Step towards Form Validation with Javascript
Before jumping in a a full data validating script it's worth starting with simpler script; one that does no validation and only submits the data:
In this example:
- the button on the form calls a Javascript function - checkFormContents
- the function checkFormContents calls a second Javascript function - validateForm
- if the validateForm function returns a true (which it always will, at the moment) then the form's submit method is used to send the data in the form
The next step is to modify the validateForm function so that it actually validates the form.
Validating Form Data With Javascript
The form validation is quite straightforward - it's just a matter of knowing what to expect and then testing accordingly; so, for example, both the first name and surname fields are required:
As well as making sure that there is an entry, the value of the entry can be validated:
and the formatting can be validated as well:
Moving on, the radio button can be validated by looking at the checked property:
and the combo-box can be validated by examining the selectedIndex property:
Conclusion
It is very easy to validate the data in an HTML form by using Javascript - it just takes a little bit of time and effort to provide that validation, but it can greatly improve a user's experience on a web site, as well as optimising the quality of the data being entered.