1. Accessibility & Legislation
  2. Common Issues
  3. Testing & Tools
  4. Analysing Your Site

2.02.04 JavaScript usage: Form validation

Example 1

A very common use of JavaScript is to validate form information. The following form will use JavaScript to allow you to confirm the information you have entered.

Enter your name in the following box, then press the Submit button.

<form method="post" action="testpage.html" onsubmit="validate(); return false;">
  <p>
    <label for="yourname">Name:</label>
    <input type="text" id="yourname" />
    <input type="button" value="Submit" onclick="validate();" />
  </p>
</form>

Problems

The confirmation and alert dialog boxes that are triggered by the onClick event are accessible to browsers and assistive technologies that have JavaScript enabled. Validating the form information with a server side script and then displaying feedback on another Web page allows you to bypass any problems that may occur in the JavaScript code and allows the form to validate if JavaScript is disabled. If JavaScript is used to validate the form, make sure that all form elements and functionality can be completed using the keyboard. Because the onClick handler is used with a form element, it is activated using both the mouse and the keyboard.

NOTE: Because most browsers will submit the form when the "Enter" key is pressed, the onsubmit event handler has been added to the <form> tag to ensure that the form will validate if the user does not activate the "Submit" button, but presses the "Enter" key while focus is in the text box. Also notice the required form label for the text box.


Example 2

This example also validates the form information, but feedback is displayed in another place within the page.

How many items are in a dozen? Enter the amount into the box below, then press the 'Check' button.

Correct, there are 12 items in a dozen.

Incorrect. There are 12 items in a dozen.

<form method="post" action="testpage.html" onsubmit="checkAnswer2(); return false;">
  <p class="invis" id="answercorrect">Correct, there are 12 items in a dozen.</p>
  <p class="invis" id="answerwrong">Incorrect. There are 12 items in a dozen.</p>
  <p>
    <label for="answerbox">Enter Answer:</label>
    <input type="text" id="answerbox" />
    <input type="submit" onclick="checkAnswer2()" value="Check" />
  </p>
</form>

Problems

The feedback is not presented in a manner that would be accessible to some assistive technologies. In this example, JavaScript is modifying the display style parameters for elements within the page to make them visible or invisible based upon the response. The screen reader user would not be aware that additional content has suddenly appeared within the page.


Solutions

  1. Validate the form information with a server side script, then display the feedback on another page.
  2. Provide the feedback in a way that is accessible, such as a JavaScript alert or another form element.

Next: Pop-up windows