JQuery and Form Validation

11 November 2011

I’ve written a post on JQuery form validation before and it became my #2 most popular post (#1 being my “like this” wordpress plugin, which also needs clean up, but that will come later…), so I figured this was something I should clean up and re-post.

View the demo

Client Side Form Validation*

Is not absolutely necessary. I say this because server-side validation is the #1 most important way to validate forms. Anything client side can’t be trusted because it’s too easy to turn off or mangle for malicious purposes.

You should always have server side validation as a back-up method, and anything client side should be an icing on the cake.

So why even bother with client side if you’re going to do it all over again on the server side?
Because reactions are quicker – the user can get instant feedback on whether they’ve filled something out correctly instead of having to press submit & wait for a page load.

*JQuery form validation is called client side because javascript is usually executed by the BROWSER (chrome, firefox…), whereas a language like PHP is executed by the SERVER (the computer the website is hosted on).

How to implement

For the sake brevity, I’m going to happily assume that you already have a beautiful HTML form set up and ready to go, and all you need is the javascript to go along with it. Feel free to view the source of the demo and use it if you want to practice.

Your first step, as ALWAYS with JQuery, is to make sure you’re including the JQuery library on your page. Right before the closing </body> tag:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

Next, for each form element that is a required field, I’m going to add a class called required. An example:

<input type="text" name="user_name" class="required">

Now I can start writing the javascript.
This code can be in its own file (called something like formValidation.js) and you can include it the same way that the jquery library was included. Make sure it’s included after the library, not before.

We’re going to check out required fields and make sure that

  1. Someone has put content in the field.
  2. The content is correct (in the case of email addresses and URLs)

If the content is all good, we’re going to add a class called good to the field. Otherwise, we’ll add a class called error. You can use CSS to decide how these two classes will look, and it’s the CSS that will trigger the user to realize that they’ve done something wrong.

$(document).ready(function() {
/* "blur" is when you exit a previously focused input field. You can change blur to keyup if you want response time AS you type. Basically, every time a required element is unfocused, the code inside the { } will be executed. */
$('.required').blur(function() {
/* Check for empty values first. */
if($(this).val().trim() == "") {
$(this).removeClass('good');
$(this).addClass('error');
}

/* Check for incorrect email data. This regex is from regular-expressions.info */
else if($(this).attr("type") == "email") {
  var regex = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;
  if(!regex.test($(this).val())) {
    $(this).removeClass('good');
    $(this).addClass('error');
  } else {
    $(this).addClass('good');
    $(this).removeClass('error');
  }
}


/* Check for valid urls. I wrote this regex myself because it wasn't as hard :P */
else if($(this).attr("type") == "url") {
  var r = /^http:\/\/\w+\.+[\w\.]+/;

  if(!r.test($(this).val().trim())) {
    $(this).removeClass('good');
    $(this).addClass('error');
  } else {
    $(this).addClass('good');
    $(this).removeClass('error');
  }
}

  else {
    $(this).removeClass('error');
    $(this).addClass('good');
  }
 });
});

This is all the code you need for instant feedback for the user. If you’re trying this out and don’t see anything happening, make sure you’ve included some CSS on your page to show the differences between inputs with a “error” class and inputs with a “good” class.

Download my form CSS for use [formstyle.css]
Download the javascript [validate.js]

Comments on this entry


  1. Jamie commented on November 22nd, 2011 at 21:05:06

    Thank you for this wonderful tutorial. I have it working beautifully, EXCEPT, I have checkboxes. They are surrounded by the fieldset tag.

    Is there a way to do it so if at least one checkbox is checked, the GOOD (check) shows up but if not the BAD (x) shows up? If you need to see my code, please let me know.

  2. Pingback: JQuery form validation part two: Checkboxes | r.osey.me

Leave a comment