Form Validation with jQuery

by Caleb Pierce on March 1, 2010

Because of jQuery’s powerful selector, it’s very easy to write form validation scripts for many different scenarios. We’ll begin by defining a class to add to form elements that can’t be left blank (including check boxes and radio buttons). I’ll use the class “notBlank” in this example. Additionally, we can define other classes such as “email” or “url” to validate for specific patterns of text, but we won’t cover that in this example.

(Optional): Insert asterisks before each required field. Notice that the span wrapping the asterisk has a class of “required”, allowing you to style it accordingly in your CSS.

$(".notBlank").before('<span class="required">*</span> ');

Next, we write the code to check the fields themselves:

$("form").submit(function(){
var thisForm = $(this); //preserve the form scope
var errors = 0; //error tracking. If it goes about 0, we know to abort form submission
var submitForm = false;

$(".notBlank",this).each(function(){
   var thisInput = $(this); //preserve the scope for inner DOM searching
   if ($(thisInput).is(":radio")){ //handle the radio buttons
      var name = $(thisInput).attr("name");
      if ($(thisForm).find(":radio[name='"+ name + "']").add(thisInput).filter(":checked").length == 0){
         errors++;
      } //if
   }
   else if ($(thisInput).is(":checkbox")){ //handle the checkboxes
      var name = $(thisInput).attr("name");
      if ($(thisForm).find(":checkbox[name='"+ name + "']").add(thisInput).filter(":checked").length == 0){
         errors++;
      }
   }
   else { //note: for a select field, the value attribute is what's checked
      if($.trim($(thisInput).val()) == '') errors++;
   }
});

if (errors > 0) {
   alert('Please check the form for empty required fields');
} //if
else submitForm = true;

return submitForm;
});

In summary, this code checks the input fields with a class “notBlank” and throws an alert and aborts form submission if a required field was left blank.

Leave a Comment