Cover by Cody Lindley

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

10.11. Validating Forms

Problem

You have a form that you would like to validate. To get started, you’ll want to set up some basic CSS. The only styles that are really important for this enhancement are the display:none declaration of the div.errorMessage selector and the display:block declaration of the div.showErrorMessage selector. The rest are just to make things look better:

<style type="text/css" title="text/css">
    div.question {
        padding: 1em;
    }
    div.errorMessage {
        display: none;
    }
    div.showErrorMessage {
        display: block;
        color: #f00;
        font-weight: bold;
        font-style: italic;
    }
    label.error {
        color: #f00;
        font-style: italic;
    }
</style>

The following HTML snippet is one example of how you might structure this form. The <div class="question> element is purely for layout and not important for the validation code. Each <label> element’s for attribute associates it with the form element with that identical id attribute. That is standard HTML, but I wanted to call it out because the JavaScript will also be using that (in reverse) to find the correct <label> for a given form element. Similarly, you’ll notice the error messages have an id attribute of errorMessage_ plus the name attribute of the associated form element. This structure may seem redundant, but radio buttons and checkboxes are grouped by the name attribute and you’d only want to have one error message per such group:

<form action="process.php"> <!-- TEXT --> <div class="question"> <label for="t">Username</label> <input id="t" name="user" ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required