| home / programming / professional / chap6/ 1 | [previous] [next] |
|
|
Now that you know how to access all form elements, you can start writing scripts for forms to make them more responsive and dynamic. We'll show you three example scripts:
The basics of form validation
Using a select box as a navigation tool
Changing the options in a select box
When your users fill in a form, it's always very important to validate the data first. After all, server-side database applications may become terribly confused if they are given a string when expecting a numeric quantity. Therefore, you should check whether the quantity field truly holds a quantity before putting the data in the database.
There are two ways of validating forms: client-side (for example, in JavaScript) and server-side (for instance, in Perl or ASP). In general, it's best to use both ways. Server-side form validation is absolutely safe since it always takes place, while client-side validation doesn't work if the user has JavaScript disabled. On the other hand, client-side validation is much quicker and saves the server some work, since the form is checked before it's sent.
JavaScript form validation starts with registering your validation function to the onsubmit event handler of the form. Thus, when the user submits the form, your script is executed first and validates the form data according to your criteria. Whenever it finds a mistake it alerts the user and cancels the submission of the form. Only when all form fields are validated correctly is the form sent to the server.
The basic syntax is:
<form name="myform" onsubmit="return
validateForm(this)">
// form elements
</form>
function validateForm(obj)
{
// obj contains the relevant form element
// Now check whatever you want to check
if (data is incorrect)
{
// alert the user and then cancel form submission
return false;
}
// If the script makes it to this line everything is OK,
// so the form can be submitted
return true;
}
Let's validate an example form.
<form name="myform" action="somescript.pl"
onsubmit="return validateForm(this)">
<input type="text" name="Name" />Name<br
/>
<input type="text" name="Address" />Address<br
/>
<input type="text" name="Country" />Country<br
/>
<input type="text" name="Email" />Email<br
/>
<input type="radio" name="test" value="1"
/>1
<input type="radio" name="test" value="2"
/>2
<input type="radio" name="test" value="3"
/>3
<input type="radio" name="test" value="4"
/>4<br />
<input type="checkbox" name="check_1" value="1"
/>1
<input type="checkbox" name="check_2" value="2"
/>2
<input type="checkbox" name="check_3" value="3"
/>3
<input type="checkbox" name="check_4" value="4"
/>4<br />
<input type="submit" value="Submit form" />
</form>

We take a simple case: all four text fields are required and at least one of the checkboxes and one of the radiobuttons must be checked.
Now let's build the validation script. We create two variables for keeping track of the radiobuttons and checkboxes. Initially these variables are false . As soon as we encounter a radiobutton or checkbox that is checked, we set the correct variable to true.
function validateForm(obj)
{
var radioChecked = false;
var checkboxChecked = false;
We then enter a for loop and go through the form elements in the order they appear in the sourcecode. First we create a short name for the current element, to avoid writing obj.elements[i] half a dozen times. Because the three types of form elements have to be validated in their own way, we read out the type of the form field.
for (var i=0; i<obj.elements.length;i++)
{
var currentElement = obj.elements[i];
var currentType = currentElement.type;
Next we test the current form element. If it's a text field, it should have a value (any value will do in this simple example). So we check if the value property has any value at all. If it doesn't, we do three things:
We alert the user of the mistake. Since the user can understand the names of the form elements, we use these names to indicate the faulty field.
When the user closes the alert, we put the focus on the correct form field. Thus the user can start typing immediately.
Finally, we return false to cancel the form submission.
if (currentType == 'text')
{
if (!obj.elements[i].value)
{
alert('You must fill in your ' +
currentElement.name + '!');
currentElement.focus();
return false;
}
}

Validating radiobuttons and checkboxes requires the same code, but they are monitored by different variables. So we give radiobuttons and checkboxes separate code branches. If the element is checked we set the correct variable to true.
if (currentType == 'checkbox' &&
currentElement.checked)
{
checkboxChecked = true;
}
if (currentType == 'radio' && currentElement.checked)
{
radioChecked = true;
}
}
Now we have gone through all form elements and done what we needed to do. We haven't finished with the radiobuttons and checkboxes, though. The next step is to see whether checkboxChecked and radioChecked are still false. If so, we once again alert the user and cancel the form submission.
if (!radioChecked)
{
alert('You should check at least one radiobutton');
return false;
}
if (!checkboxChecked)
{
alert('You should check at least one checkbox');
return false;
}
return true;
}

Only when the form has passed this last test, do we return true
to indicate that the form submission can proceed: all data is valid.
| home / programming / professional / chap6/ 1 | [previous] [next] |
Created: March 11, 2003
Revised: March 11, 2003
URL: http://webreference.com/programming/professional/chap6/1