Easy jQuery Form Validation

Form’s can be a hassle. You have either incomplete forms, or you loads of spam… And no one wants either of those. That’s where form validation comes in. Not only will it help catch when someone has not filled in all the required information, but it also creates less of a headache for you. And let’s face it, you don’t want to waist all that Ibuprofen on yourself now do you? :-P

View Example

This post addresses browser side validation – specifically, JavaScript and jQuery.

There are several ways to create a validation system with your forms and jQuery. This is a method I find easiest, and a great starting point for anyone wanting to create their own validation (rather than use a plugin). Why not use a plugin? Plugins are great, but often come way too bloated with features you don’t use. By using this method, you can custom tailor your validation script to fix exactly what you need, nothing more or less.

The basic usage of this validation is through the use of classes. What classes? Well, whatever you want. You can work out whatever system is best for you. For the purposes of this post, I am going to use the following structure:

  • Form class: “validate”
  • Required class: “req”
  • Email class: “req-email”
  • Phone class: “req-phone”

Here is the basic HTML setup:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<form class="validate">
  <div>
    <input type="text" name="name" class="req" />
  </div>
  <div>
    <input type="text" name="email" class="req req-email" />
  </div>
  <div>
    <input type="text" name="phone" class="req req-phone" />
  </div>
  <div>
    <input type="text" name="website" />
  </div>
  <div>
    <textarea name="message" class="req"></textarea>
  </div>
  <input type="submit" name="submit" value="Submit" />
  <span class="error-message"></span>
</form>

The only requirements for your HTML structure is that each input needs to be in it’s own element (in this case, a <div>), and an element with the class ‘error-message‘ that will display ‘Please correct the above errors‘. Beyond that, you can adjust this how you see fit.

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$('form.validate').submit(function() {							 
  $(this).find('div span').remove();
  $(this).find('span.error-message').hide();
 
  var valid = true;
  $(this).find('.req').each(function() {
    if ($(this).val() == "") {
      $(this).after('&lt;span>Required!&lt;/span>');
      valid = false;
    } else if ($(this).hasClass('req-email') && !checkemail($(this).val())) {
      $(this).after('&lt;span>Invalid E-mail!&lt;/span>');
      valid = false;
    } else if ($(this).hasClass('req-phone') && checkphone($(this).val())) {
      $(this).after('&lt;span>Numbers Only!&lt;/span>');
      valid = false;
    }
  });
  if (!valid) {
    $(this).find('span.error-message').text("Please correct the above errors.").show();
    return false;
  }
});
function checkemail(e){
  var emailfilter = /^w+[+.w-]*@([w-]+.)*w+[w-]*.([a-z]{2,4}|d+)$/i
  return emailfilter.test(e);
}
function checkphone(e) {
 var filter = /[0-9]/
 return filter.test(e);
}

The variable valid is used to determine at the end of the script if the form is valid. If it is set to false, the form is not valid and will display the errors, overriding the submit action (return false). If valid is set to true, then the form is valid and is submitted as usual.

Breakdown

1
2
3
$(this).find('.req').each(function() {
  // code
});

This snippet of the code finds each element in the form with the class req. If you are using a different class to denote a required field, make sure to change it here too.

1
2
3
4
if ($(this).val() == "") {
  $(this).after('&lt;span>Required!&lt;/span>');
  valid = false;
}

This determines if the input in blank. If it is blank, then the error message (<span>) is appended after the input, and the valid variable is set to false.

1
2
3
4
5
6
7
8
if ($(this).hasClass('req-email') && !checkemail($(this).val())) {
  $(this).after('&lt;span>Invalid E-mail!&lt;/span>');
  valid = false;
}
function checkemail(e){
  var emailfilter = /^w+[+.w-]*@([w-]+.)*w+[w-]*.([a-z]{2,4}|d+)$/i
  return emailfilter.test(e);
}

This snippet determines if the input has the class req-email, and if it doesn’t have a valid email by running it through the checkemail() function. Read more about this function here.

1
2
3
4
5
6
7
8
9
if ($(this).hasClass('req-num') && checknum($(this).val())) {
  $(this).after('&lt;span>Numbers Only!&lt;/span>');
  valid = false;
}
 
function checknum(e) {
 var filter = /[0-9]/
 return filter.test(e);
}

The first part of this code determines if an input has a class of req-num, and tests to see if the function checknum() returns true. The checknum() function tests the string with a Regular Expression, to determine if it only contains numbers.

Feel free to change the expression to how you see fit. As is, it allows a string of any length containing only numerals. Here’s an example of an advanced expression:

1
2
3
4
function checknum(e) {
 var filter = /^D?(d{3})D?D?(d{3})D?(d{4})$/
 return filter.test(e);
}

This expression is great for US phone numbers. It will accept the following inputs:

1112223333
(111) 222-3333
111-222-3333

Demo

The thing to keep in mind is don’t include anything your not going to use. If you have no need for email validation, don’t include it!

View Example

You can style the form however you’d like. You can take a look at the demo source code for a styling example.

Disclaimer

When it comes down to it, the best form of validation is done server side (php/asp ect). Simply having JavaScript handle your validation isn’t enough. If someone has JavaScript turned off, they’d bypass your validation. Also, anyone with knowledge on how to manipulate the DOM could simply override your JavaScript.

So why bother with JavaScript validation? It adds more dynamic user interactivity for your visitors, and it’s quicker than having to load a page after it’s submitted. It’s all about your preference.

August 31st, 2009 | jQuery

3 Responses to “Easy jQuery Form Validation”

  1. LOVE the code – LOVE your site styling
    excellent!

  2. Thank you so much for sharing this code.

  3. Hi! I like your solution very much. For fast and easy validation, this is a breeze.

    Regards,
    AJ

1 Pinback/Trackback to “Easy jQuery Form Validation”

Leave a Reply

Name:
Email:
Website:
Message:
SUBMIT