Article Image
read

In just one week, I have encountered this problem twice, so I think it's worthy of a post.

The problem was that a form needed to provide negative feedback while the user was entering data. I find this to be more useful than an all at once "You're missing <this> and <that>. Go back and fill them out or I will never accept your submission."

What better to solve this issue than the worlds greatest Javascript library, jQuery!

Most standard forms consist of multiple sets of labels and an inputs. To simplify this example, lets collect a user's first and last names, street address and favorite number. All fields except street address are required and will be validated against their appropriate data type.
So the form looks something like this...

So far, so normal. Next, lets add a way to differentiate required from optional fields. We'll do this by adding the "required" CSS class to the fields.

Now to tell jQuery to listen for changes to those required elements

$( function(){
  $(':input.required').bind('blur', function(){
    // Display our error here
  });
});

Ok, so now we're bound to the Blur event of the fields with class 'required' that are input fields. Now we need a place to display the errors. I prefer to show them as close as possible to the field that the error was caused by. I've accomplished this in two different ways.

One way is by adding a <span> or <div> where you'd like your error to appear. The con of this is that you have to add that field. The pro is that you have more control over the error display (could be useful with multiple fields on one line).

The other way (which I'll demonstrate) is to dynamically add a span or div when a required field is not entered or entered incorrectly.

$(function(){
$(':input.required').bind('blur', function(){
   var myName = $(this).attr('name');
   if( $(this).val().length == 0 ){
      $('.warning.' + myName).remove();
      // Display our error here
      var warning = $('');
      var prettyName = $('label[for='+myName+']').text();
      $(warning).addClass(myName)
         .html(prettyName + " is required!")
         .insertAfter($(this));
      $(this).addClass('error');
   }else{
      // Clear errors
      $(this).removeClass('error');
      $('.warning.' + myName).remove();
   }
});
});

Thats all there is to it. We've accomplished telling the user that his input was incorrect. All formatting issues are taken care of with the CSS (see example below) and the javascript keeps the form markup to the point.

Links

Live Example

Blog Logo

Jon Dowdle

Jon Dowdle currently works on the internet at a lovely place called InVision.


Published

Color

Jon Dowdle's Blog

The personal blog of Jon Dowdle.

Back to Overview