Making Form Fields Mandatory
It's common for a form to contain at least one field that the user must fill in. For example, there isn't any ethical way to determine the user's email address automatically, so you need to ask the user to enter it in a form field. If it's important that you contact the user, then you probably want to set up the form field so that the submission won't go through unless the email field is filled in.
Here are a few things you can do to encourage users to fill in mandatory fields:
Make it clear which fields are mandatory. Many sites place an asterisk before or after a field and include a note such as Fields marked with * are mandatory at the top of the form.
For a radio button group, always set up your form so that one of the <input> tags includes the checked attribute. This ensures that one option will always be selected.
For a selection list, make sure that one of the <option> tags includes the selected attribute.
If you've done all this, then the only thing left to do is to use some JavaScript to check for Text, Textarea, Password, or FileUpload fields that have not been filled it. The next few sections present functions that perform this type of validation.
CAUTION
The functions in the next few sections essentially look for fields that aren't empty or that don't contain only whitespace (such as a tab). Bear in mind, however, that this doesn't mean you're assured of getting valid data. It simply means that you won't get the most trivial data.
First, a Trick: Adding Custom Properties to an Object
In the previous section, you saw that creating a generic display function was much easier in the long run than hard-wiring field names into the script. It appears on the surface that we might not be able to do the same thing for mandatory fields. For a generic function to work, it needs to be able to loop through all the form fields. Because we're only interested in text fields, we can narrow things down by looking for fields with a type property value of text, textarea, or password. But then what? Once we have a text field, how does a generic function know whether the field is mandatory or not?
The secret to solving this problem is that you can create "custom" properties for an object. These are temporary properties that last only as long as the user visits your page, but that's all we need. To set up a custom property, you use the following syntax:
Object.Custom_Property = Initial_Value
Object |
The object to which you want to assign the custom property |
Custom_Property |
The name of the custom property |
Initial_Value |
The initial value of the custom property |
To get around our problem, we could assign a property named mandatory to each text object and initialize this property to true for the mandatory field, and to false for the optional fields. You need to do this using statements that run while the page loads but after the form loads. Listing 1 provides an example.
Listing 1: Working with a Custom Property
<html> <head> <title>Listing 29.3. Working with a Custom Property</title> </head> <body bgcolor="#FFFFFF"> <form> <b>Custom Property:</b> <br> <input type="text" name="text_field"> <p> <input type="button" value="Toggle Custom Property" onClick="toggle_custom_property(this.form.text_field)"> </form> <script language="JavaScript" type="text/javascript"> <!-- document.forms[0].text_field.mandatory = true document.forms[0].text_field.value = true function toggle_custom_property(current_field) { // Get the current value of the mandatory property var current_value = current_field.mandatory // Set the property to the opposite value current_field.mandatory = !current_value // Display the new value in the field current_field.value = current_field.mandatory } //--> </script> </body> </html>
Notice, first of all, the first two statements in the <script> block. These execute after the form has been loaded by the browser. The first one assigns a custom property named mandatory to the field named text_field and sets this property to true:
document.forms[0].text_field.mandatory = true
The Button object runs the toggle_custom_property() function and sends the Text object as the argument. In this function, the value of the mandatory property is stored in current_value, the opposite of this value is stored in the mandatory property, and then this new value is displayed in the text box.
What this means is that you can set up all your form's text fields with the mandatory property (or whatever you prefer to call it) and set it to true for those fields that the user must fill in, and set it to false for optional fields. With that done, your validation loop would be set up like this (assuming that current_form is a reference to the Form object):
for (counter = 0; counter < current_form.length; counter++) { if (current_form[counter].type=="text" && current_form[counter].mandatory) { // Make sure current_form[counter] has been filled in. } }
Note, too, that my if() test ignores Textarea and Password objects to make the code readable. In practice, you'd include these objects in the if() statement (as I do in Listing 2).
Checking for Empty Fields
The simplest validation is to see whether a mandatory field is empty. Here's a function that returns true if the string_value argument is either the empty string ("") or null:
function its_empty(string_value) { // Check for the empty string and null if (string_value == "" || string_value == null) { // If either, it's empty so return true return true } // Otherwise, it's not empty so return false return false }
TIP
Here's a more efficient version of the its_empty() function:
function its_empty(string_value) { return (string_value == "" || string_value == null) { }
Listing 2 shows how you'd incorporate this function into a validate() function that's called by a button object.
Listing 2: Checking for an Empty Field
<script language="JavaScript" type="text/javascript"> <!-- function validate(current_form) { var missing_fields = new Array() var total_missing = 0 // Loop through all the form elements for (counter = 0; counter < current_form.length; counter++) { // Is this a visible text field that's mandatory? if ((current_form[counter].type == "text" || current_form[counter].type == "textarea" || current_form[counter].type == "password") && current_form[counter].mandatory) { // Is it empty? if (its_empty(current_form[counter].value)) { // If so, add the field to the array of missing fields missing_fields[total_missing] = current_form[counter] total_missing++ } } } // Were there any fields missing? if (total_missing > 0) { // Start the message var missing_message = "Sorry, you must fill in the following " + (total_missing == 1 ? " field:" : " fields:") + "\n______________________________\n\n" // Loop through the missing fields for (counter = 0; counter < missing_fields.length; counter++) { missing_message += missing_fields[counter].name + "\n" } // Finish up and display the message missing_message += "\n______________________________\n\n" + "Please fill in these fields and then resubmit the form." alert(missing_message) // For emphasis, put the focus on the first missing field missing_fields[0].focus() } else { // Otherwise, go ahead and submit current_form.submit() } } function its_empty(string_value) { // Check for the empty string and null if (string_value == "" || string_value == null) { // If either, it's empty so return true return true } // Otherwise, it's not empty so return false return false } //--> </script>
The validate() function begins by setting up an array named missing_fields that will be used to hold each mandatory field that hasn't being filled in. The variable total_missing tracks the number of missing fields. Note, as well, that the two text fields are set up as mandatory using the following code that appears after the form:
<script language="JavaScript" type="text/javascript"> <!-- // Make the two Text fields mandatory document.forms[0].Your_Name.mandatory = true document.forms[0].Your_Email.mandatory = true //--> </script>
The function then loops through the form fields looking for those with the type property of text, textarea, or password, and with the custom mandatory property set to true. If it finds such a field, the field's value is sent to the its_empty() function. If that function returns true, the field is added to the missing_fields array and total_missing is incremented.
When the loop is done, the function checks the value of total_missing. If it's greater than 0, a message to the user is initialized in the missing_message string and a for() loop adds the name of each missing field to the message. The message is then displayed to the user, and the focus is moved to the first missing field.
Checking for Fields That Contain Only Whitespace Characters
A user could try to get around your is_empty() function by entering one or more spaces or by pressing Enter within a text area. To fill these loopholes, use the its_whitespace() function in Listing 3.
Listing 3: Checking for Whitespace-Only Fields
function its_whitespace(string_value) { // These are the whitespace characters var whitespace = " \n\r\t" // Run through each character in the string for (var counter = 0; counter < string_value.length; counter++) { // Get the current character current_char = string_value.charAt(counter) // If it's not in the whitespace characters string, // return false because we found a non-whitespace character if (whitespace.indexOf(current_char) == -1) { return false } } // Otherwise, the string has nothing but // whitespace characters, so return true return true }
The function begins by initializing the whitespace variable to hold a string containing all the possible whitespace characters: space, newline (\n), carriage return (\r), and tab (\t). Then a for() loop runs through each character in the string_value argument. With each pass, the current character is extracted using the charAt() method and stored in the current_character variable. Then the indexOf() method is used to see if current_character is in whitespace. If it's not, indexOf() returns -1, and it means we've found a non-whitespace character, so the function returns false. If we make it out of the loop, then it means that the string contained only whitespace characters, so the function returns true.