Validating Forms with jQuery

When a user fills out a form, you can increase the chances of the user providing all the information you need by validating the form: rejecting the submission and giving the user feedback about what's wrong, if the provided information is incomplete or invalid.

Client-Side and Server-Side Validation

There's two fundamentally different ways to do form validation:

  1. Server-side validation occurs only after the form is submitted
  2. Client-side validation can occur dynamically, while the user is completing the form

Server-side validation is the most robust, in that it can't be bypassed by disabling JavaScript or otherwise modifying the front-end code, and it is important when you are submitting information directly into a business-critical database with strict requirements.

It has a couple of drawbacks, however. First, it is only performed after the form is submitted, and must wait for a response from the server, so the user experience is not great. Second, it requires that the back-end code be customized to meet the needs of each form.

Webvanta uses primarily client-side validation for public forms. Usually, any information submitted is reviewed by an administrator in any case, and what's most important is that the user have a good experience.

Validating with JavaScript

In concept, client-side validation is simple. JavaScript observers are placed on each form field, and when the user enters information, the JavaScript code validates its format and, if necessary, displays an error message and blocks the form from being submitted.

In practice, form validation is a complex technical and user experience challenge, and it requires a substantial amount of JavaScript programming. Fortunately, as with most web site features that cry out for JavaScript, there's an excellent jQuery Validation plugin available.

To use this plugin to validate your forms, you need to do three things:

  1. Load the jQuery library and the form validation plugin in the head section of your page.
  2. Configure the form and plugin so they behave how you want.
  3. Invoke the validation function on the form.

Loading the Plugin Code

To use client-side validation, make sure jQuery is loaded in the head section of the page, and then load the form plugin and the validation plugin. For a Webvanta site, you can use:

<script src="/webvanta/js/jquery/1.4/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="/webvanta/js/jquery/1.4/plugins/form/jquery.form.js" type="text/javascript"></script> <script src="/webvanta/js/jquery/1.4/plugins/validate/jquery.validate.min.js" type="text/javascript"></script>

In this example, we've loaded the code from the shared "/webvanta" library — these files are not directly visible within your site's admin interface, but they are available to all Webvanta sites (see Accessing Open-Source Library Files for details).

Invoking the Validation

Once the code has been loaded, invoking the validation plugin is simple:

$("#myform").validate();

The ID (myform) tells the plugin where to find your form. The validation plugin code then hooks itself into the form, observing the fields and blocking the submit action until validation passes. The ID in the JavaScript above must match that of the HTML form element:

<form id="myform" action="/...">

The JavaScript code must, of course, be in a script block, and it must not be executed until the form has been created and the HTML document is ready for JavaScript to work with it. Here's a more complete example:

<script type="text/javascript">
  $(document).ready(function() {
    $("#myform").validate({
        [validation options go here]
    });
  });
</script>

Configuring the Validation

Now that the validation plugin is loaded and has been invoked on your form, all that remains is to configure the plugin for the form.

There are many things you might want to configure:

  • Which fields are required
  • Which fields require content in certain formats, such as email addresses or phone number
  • What message is displayed for each field when validation fails
  • What summary is displayed at the top of the form when validation fails

There are two different ways you can specify the per-field requirements:

  1. Add metadata, in the form of special classes, to each field
  2. Specify everything when invoking the validation plugin

The first approach is simpler if you're happy with the default behavior. For example, if you just want to make certain fields required, add

class = "required"

to each required form field element (e.g., input, textarea).

It feels a little more technical, but is much more powerful, to configure the validation in JavaScript when you invoke the plugin. You can specify custom validation rules, combinations of rules, and message text, and all of the validation settings are in one place, instead of being scattered throughout your HTML code.

You must have a "name" attribute on every form field, because it is the name, not the ID, that you specify when setting validation options. (You'll probably also want to have an ID on each element, so you can associate the label with the element.) The name and ID don't need to be the same, but it's generally simplest to keep them that way:

<label for="firstname">Firstname</label><input id="firstname" name="firstname" />

Setting Options

The range of options you can specify can be daunting; the full list is in the jQuery validation plugin options documentation. In most cases, though, you'll ignore almost all of them and stick with a simple set.

The options are all name/value pairs, which means that the syntax is as follows:

$("#myform").validate({
    option-name: option-value,
    option-name: option-value,
    option-name: option-value
});

You can specify as many options as you need. The option value can be a simple string, but more often it will itself be an array of values, which itself may be an array of values, with each array surrounded by curly braces ( { } ). (The syntax may be confusing at times, but it is standard JavaScript notation.)

There are two options that you'll use primarily: rules and messages. For each, you provide an array of settings, one for each field you want to validate, as this example illustrates:

$("#myform").validate({
   rules: {
     name: "required",
     email: {
       required: true,
       email: true
     }
   },
   messages: {
     name: "Please specify your name",
     email: {
       required: "We need your email address to contact you",
       email: "Your email address must be in the format of name@domain.com"
     }
   }
})

Note: In the example above, the strings "name" and "email" must match the name attribute of the corresponding form field. If the name has brackets in it, as all Webvanta-generated forms do, then you must enclose the name in quotes.

In this code, we've set up validation for two fields: name and email. The name field is required, but has no other constraints; the email field is both required and must pass muster as a possibly valid email address. These settings are all part of the rules option.

If you don't specify the messages, defaults will be provided, but generally you'll want to customize them. The example above shows how you can provide different messages for the same field, depending on which validation rule fails; it's better to say that the email address is needed, if is left blank, than to say that it is invalid (which is what would happen if you used a single message).

With a little JavaScript programming, you can customize the behavior of the validation plugin extensively (see the docs cited earlier), but you may be happy enough with just setting the rules and the messages.

Styling Messages

The validation plugin is simply inserting HTML elements into your page to display messages and highlight invalid fields. You can control the markup it uses and, of course, you can style the classes however you want in your CSS files.

The options documentation has an extensive list of classes that you can specify.

If you just want to style the classes that are applied by default, use FireBug to identify the class names by testing your form with the validation plugin running, and then create your own CSS rules for these classes.