Article

JavaScript 101 - Part 3

Page: 1 2 3 4 5 6 Next

Validating Other Form Elements

Checking that required text fields are filled in is all well and good, but there is more to your average form than a few text fields and a submit button. In this section, we’ll see ways to validate checkboxes, radio buttons, lists, and text areas.

A checkbox is created with an input tag like this:

<input type="checkbox" name="myCheckbox" value="someValue">

A checkbox’s value is accessible as its value property, just like that of a text field. An additional property called checked, however, lets you determine if a given checkbox is checked. Thus, if you had a group of checkboxes (say they were named myCheckbox1, myCheckbox2, and so on) and required that at least one be checked for the form to be submitted. The JavaScript code to check this would look like this:

if (!theForm.myCheckbox1.checked && !theForm.myCheckbox2.checked &&    
   !theForm.myCheckbox3.checked && !theForm.myCheckbox4.checked ) {    
 alert("Please select at least one checkbox.");    
 return false;    
}

The && operator in the above is the logical AND operator. It lets you combine two conditions to form a single compound condition that will be true if and only if both of the basic conditions are true. We have also used !, the logical NOT operator, which makes a condition true if it is false and vice versa. Thus, the above code may be read as follows:

If myCheckbox1 is NOT checked AND myCheckbox2 is NOT checked AND myCheckBox3 is NOT checked AND myCheckBox4 is NOT checked, then display a message and return false.

Another way of doing this is to use the logical OR operator (||) instead:

if (!(theForm.myCheckbox1.checked || theForm.myCheckbox2.checked ||    
   theForm.myCheckbox3.checked || theForm.myCheckbox4.checked)) {    
 alert("Please select at least one checkbox.");    
 return false;    
}

The logical OR operator lets you combine two conditions to form a single compound condition that will be true if any of the basic conditions are true. Note also that we’ve surrounded the condition formed with four || operators with parentheses and inverted it using the ! operator. Thus, the above code may be read as follows:

If the following is NOT true, display a message and return false: myCheckbox1 is checked OR myCheckbox2 is checked OR myCheckbox3 is checked OR myCheckbox4 is checked.

If you think about this for a little while, you should be able to see that this paragraph is equivalent to the one above. Use whichever you prefer – they will both work.

Radio buttons are very similar to checkboxes:

<input type="radio" name="myRadio" value="someValue">

The difference is that radio buttons are normally specified in groups that share the same name attribute, and only one of each group of radio buttons can be selected. You can force the user to select one of a group of radio buttons by adding the checked attribute to one of the input tags as follows:

<input type="radio" name="myRadio" value="someValue" checked>

That radio button will be selected by default when the page loads, and there is no way for the user to deselect it without selecting another. Thus, in cases where it makes sense to have a default choice for the user, no validation is necessary for radio buttons.

At times, however, no default choice makes sense (e.g. two radio buttons that let the user specify if he or she is male or female), and none of your radio buttons will be selected by default. In such cases, validation can be done in a similar fashion to checkboxes, checking the checked property of each in turn to see if it has been selected. Since radio buttons in a group share the same name, however, the myForm.myRadio reference will actually be an array of the radio buttons in that group. The code to check that one is selected, then, is as follows:

if (!theForm.myRadio[0].checked && !theForm.myRadio[1].checked &&    
   !theForm.myRadio[2].checked && !theForm.myRadio[3].checked ) {    
 alert("Please select a radio button.");    
 return false;    
}

Or alternatively:

if (!(theForm.myRadio[0].checked || theForm.myRadio[1].checked ||    
   theForm.myRadio[2].checked || theForm.myRadio[3].checked)) {    
 alert("Please select a radio button.");    
 return false;    
}

Since we’re dealing with an array, a for loop can also be used:

var radioSelected = false;    
for (var i=0; i<theForm.myRadio.length; i++) {    
 if (theForm.myRadio[i].checked) radioSelected = true;    
}    
if (!radioSelected) {    
 alert("Please select a radio button.");    
 return false;    
}

This last option may look longer at first glance, but if you’ve got many radio buttons in your group, you’ll find it can save quite a bit of typing.

Lists are created in HTML with a select tag containing a number of option tags:

<select size="1" name="myList">    
 <option value="" selected>Please choose an option</option>    
 <option value="1">One</option>    
 <option value="2">Two</option>    
 <option value="3">Three</option>    
</select>

As for radio buttons, you can specify a default selection (selected), which will often relieve any need for validation to force the user to choose an option. In the case of drop-down lists, however, (where size="1" as in the above example), the first item in the list is often used (again, as in the example above) to display some sort of prompt for the user, and you want to ensure that they have chosen one of the other options.

The trick here is to notice that you can specify a value for each element in the list. By setting the value of the first item (and any other non-acceptable choices) in the list to an empty string as above, your JavaScript verification code can then check if the value of the selected item is an empty string or not! Here’s the JavaScript code involved:

if (theForm.myList[theForm.myList.selectedIndex].value == "") {    
 alert("Please make a valid selection from the list.");    
 return false;    
}

You’ll notice that, as in the case of radio buttons, the DOM object representing the list is actually an array of the elements contained therein. To gain access to the currently selected element, you retrieve its index from the selectedIndex property of the list. Thus, if the third element in the list was selected, theForm.myList.selectedIndex would equal 2 (remember, the first item in an array has index 0). Then theForm.myList[2].value would give the value of the currently selected list item! Checking if this is "" (the empty string) lets us determine if an invalid item is currently selected.

By and large, text areas can be validated in the same way as regular text fields, which we treated at length at the beginning of this article. One question I am frequently asked, however, is how to limit the number of characters that can be entered into a text area, in order to enforce stated limitations such as “up to 255 characters”. As it turns out, this is quite easy to do. Simply retrieve the value property of the text area, which contains the string of text that has been entered, and then check its length property (which all strings have):

if (theForm.myTextArea.value.length > 255) {    
 alert("You are over the limit of 255 characters! You typed " +    
       theForm.myTextArea.value.length + " characters.");    
 return false;    
}

Note that on Windows computers, typing Enter to start a new line in a text area actually inserts two invisible characters (a carriage return and a new line), which count towards the character limit.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links