O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required