Validating form input with JavaScript is easy to do and can save a
lot of unnecessary calls to the server as all processing is handled by
the web browser. It can prevent people from leaving fields blank, from
entering too little or too much or from using invalid characters.
For an alternative approach to client-side form validation, without
JavaScript, check out our new article on HTML5 Form Validation which is
available now in most modern browsers.
Note: When the form input is important, it must always
be checked or re-checked by using a server-side script. Otherwise a
browser with JavaScript disabled, or a hacker trying to compromise your
site, can easily submit invalid data.
Restricting input to alphanumeric characters
In the following example, the single input box, named input,
must: a) not be empty; and b) contain only alphanumeric characters and
spaces. Only if both tests are passed can the form be submitted.
<script type="text/javascript">
function checkForm(form)
{
// validation fails if the input is blank
if(form.inputfield.value == '') {
alert("Error: Input is empty!");
form.inputfield.focus();
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w ]+$/;
// validation fails if the input doesn't match our regular expression
if(!re.test(form.inputfield.value)) {
alert("Error: Input contains invalid characters!");
form.inputfield.focus();
return false;
}
// validation was successful
return true;
}
</script>
Note: The pre-defined class \w represents any
alphanumeric character as well as the '_' character.
The regular expression ^[\w ]+$ will fail if the input is
empty as it requires at least one character (because we used +
instead of *). The first test in the example is therefore only
necessary in order to provide a different error message when the input
is blank.
The purpose of a form validation script is to return a boolean value
(true or false) to the onSubmit event handler. A
value of true means that form will be submitted while a
false value will block the form from being submitting. The
focus() command is used to set the focus to the problem element.
You can test the above script with different input values using this
form:
The form is put together as follows:
<form method="POST" action="action" onSubmit="return checkForm(this);">
Input: <input type="text" size="32" name="input"> <input type="submit">
</form>
The name attribute of the input field is used to reference
that field from within the checkForm function. With the advent
of DHTML it's tempting to use id's to
reference form fields, but that can lead to namespace conflicts and why
make things more complicated than necessary.
When the form is submitted - either by hitting Enter or clicking on
the Submit button - the onSubmit handler is triggered. This
then calls our checkForm() function, passing a reference to
itself (the form) as the only variable. This makes the value of the
input box available within the function as form.input.value
(the 'value' of the field called 'input' belonging to the form). Other
form values are available using a similar syntax, although this becomes
more complicated if you're using SELECT lists, checkboxes or radio
buttons (see below for examples).
The checkForm function tests the form input against our
conditions, returning a value of true if the form is to be
submitted (when all tests have been passed) or false to abort
(cancel) the form submission. It's that simple.
In a real-life situation you will most likely have more fields to
check, and more complicated conditions, but the principle remains the
same. All you need to do is extend the checkForm function to
encompass the new fields and conditions:
function checkForm(form)
{
if(!condition1) {
alert("Error: error message");
form.fieldname.focus();
return false;
}
if(!condition2) {
alert("Error: error message");
form.fieldname.focus();
return false;
}
...
return true;
}
When a return command is encountered, execution of the
function is halted. In other words if the first condition fails, the
second condition will not be tested and so forth. Only when all
conditions have been satisfied do we reach the return true
command, in which case the form will be submitted.
You'll see that the all validation scripts presented on this and
subsequent pages adhere to the same basic format.
Working with different types of FORM elements
Text/Textarea/Password boxes
The value of a text input box (or a textarea or password input) is
available using the syntax form.fieldname.value. This is
not the case for other input types.
form.fieldname.value
To check whether two inputs have the same is quite simple:
if(form.field1.value == form.field2.value) {
// values are identical
}
Note: Make sure to always use == for
comparisons. If you use = (the assignment operator) instead
then it can take a long time to debug.
and to see if they have different values we just reverse the logic:
if(form.field1.value != form.field2.value) {
// values are different
}
If you want to test numeric values (or add or subtract them) then you
first have to convert them from strings to numbers. By default all form
values are available as strings only.
var field1 = parseInt(form.field1.value);
var field2 = parseInt(form.field2.value);
if(field1 > field2) {
// field1 as a number is greater than field2 as a number
}
Note: parseFloat is the same as
parseInt except that it works for floating point
numbers as well as integers.
Select/Combo/Drop-down boxes
The value of a SELECT input element is accessed using:
var selectBox = form.fieldname;
selectBox.options[selectBox.selectedIndex].value
selectBox.options[selectBox.selectedIndex].text
where fieldname is the SELECT element, which has an array of
options and a value selectedIndex that tells you which
option has been selected. The illustration below shows this
relationship:
Note that the 'I' in selectedIndex needs to be capitalised -
JavaScript functions and variables are always case-sensitive.
If you define a value for the OPTION elements in your SELECT
list, then .value will return that, while .text will
return the text that is visible in the browser. Here's an example of
what this refers to:
<option value="value">text</option>
Note: One of the most common problems for novices is that
Internet Explorer allows you to access the value of the selected option
using the same format as for text boxes above. This is wrong!
If you just want to check that an option has been chosen (ie. that
the SELECT box is no longer in it's default state) then you can use:
if(form.fieldname.selectedIndex > 0) {
// an option has been selected
} else {
// no option selected
}
Checkboxes
These really are simple:
form.checkboxfield.checked
will return a boolean value (true or false) indicating whether the
checkbox is in a 'checked' state.
function checkForm(form)
{
if(form.checkboxfield.checked) {
alert("The checkbox IS checked");
} else {
alert("The checkbox IS NOT checked");
}
return false;
}
Note: You don't need to test using
form.checkboxfield.checked == true as the value is already
boolean.
Radio buttons
Radio buttons are implemented as if they were an array of checkboxes.
To find out which value (if any) has been selected, you need to loop
through the array until you find which one has been selected:
function checkRadio(field)
{
for(var i=0; i < field.length; i++) {
if(field[i].checked) return field[i].value;
}
return false;
}
The form handler function is then the following:
function checkForm(form)
{
if(radioValue = checkRadio(form.radiofield)) {
alert("You selected " + radioValue);
return true;
} else {
alert("Error: No value was selected!");
return false;
}
}
Checkbox arrays
If you're working with arrays of checkboxes to submit data to a
server-side script then you might already have some grey hairs from
trying to figure out how to validate the input using JavaScript.
The problem is that, to have the data submitted in a 'nice' format to
the server, the name attributes of all the checkboxes in the
array are often set to the same value: a name ending with [].
This makes it difficult to address them directly using JavaScript.
In this example, the checkboxes are defined as:
<input type="checkbox" name="pref[]" value="value"> label
When you submit the form you will be notified through an alert
message how many items you checked, and what they were. This is
calculated using a new function:
// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function checkArray(form, arrayName)
{
var retval = new Array();
for(var i=0; i < form.elements.length; i++) {
var el = form.elements[i];
if(el.type == "checkbox" && el.name == arrayName && el.checked) {
retval.push(el.value);
}
}
return retval;
}
The form handler that calls this function and displays the alerts is
as follows:
function checkForm(form)
{
var itemsChecked = checkArray(form, "pref[]");
alert("You selected " + itemsChecked.length + " items");
if(itemsChecked.length > 0) {
alert("The items selected were:\n\t" + itemsChecked);
}
return false;
}
The checkArray function returns an array contains all the
select values.
Normally you would modify this so that you could submit or not submit
the form based on the number of items selected. For example "at
least two" or "no more than five". This should be a
simple exercise.
Combining Form Elements in Conditions
In more complicated forms you will want to set conditions on the form
that combine multiple elements. For example, a text input that only
needs to have a value if a checkbox is checked:
function checkForm(form)
{
...
if(form.checkboxname.checked && (form.textinputname.value == '')) {
alert('Error: error message');
form.textinputname.focus();
return false;
}
...
}
or conditions that vary according to a radio button selection:
function checkForm(form)
{
...
var radioValue = checkRadio(radiofield);
switch(radioValue)
{
case 'Red':
conditions to apply if 'Red' is selected
break;
case 'Blue':
conditions to apply if 'Blue' is selected
break;
default:
conditions to apply in all other cases
}
...
}
Using simple logical operators and the functions supplied above you
can do all sorts of client-side form validation. To take things a step
further you can even explore Ajax
Form Validation which lets you supply real-time feedback using
server-side scripts triggered by JavaScript events.
Related Articles
|