Home > Articles > Web Development > Ajax and JavaScript

Making Form Fields Mandatory

Forms generally require the user to fill in at least one field. Paul McFedries shows you some ways to encourage users to fill in mandatory fields.
This article is excerpted from Special Edition Using JavaScript.
Like this article? We recommend

Like this article? We recommend

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020