< Back

Darth Validator: Not Just Another jQuery Form Validator

Actually, the post's title may be a little misleading.  It should've been, "Darth Validator: Just Another jQuery Form Validator."  Well, what's done is done.  You're here and you ain't leaving.  And just to make sure, i've implemented the latest scammy javascript technique of completely searing this blog post into your glossy-liquid display.  Just try closing this window… Sorry, no more silliness.

One morning, feeling particularly peachy, I came across the need to some client-side form validation.  As a general rule of thumb, if it takes me longer to find a plugin and read it's documentation than it would be to write it myself, I tend to favor the latter (if I even attempted the former, it would've lead me to this — a beautiful feature-rich jQuery validator).  So, having nothing better to do than write some scripty-goodness, I embarked on a form validation quest with the added benefit of learning how to extend jQuery.

Objective

Create a jQuery function that will add special validating powers to a HTML form.  Secondly, it has to validate when an element loses focus, because I like it and it makes me feel special.  Thirdly, it has to be written so haphazardly that it should never be used in a production environment, ever.

Step 1: Extend jQuery Object

  $.fn.darthValidator = function(vars) { ... };

Wrap your logic in a pretty jQuery wrapper.  We use this to add our new function "darthValidator" so it can be accessed via normal jQuery syntax like $('#form').darthValidator(); and, handling "vars" for any custom arguments.

Step 2: Hook Up Events When Object is Initialized

// on startup, hook up blur events to each form field
 $(this).find('input').each(function(index) {
  field_blur($(this));
 });
 
 // hook up submit function
 form.submit(function() {
  is_valid = true;
  
  // iterate through fields and initiate blur event, checks errors
  $(this).find('input').each(function(index) {
   $(this).blur();
  });
  
  // let form submit if no errors were found
  return is_valid;
 });

So, as I see it, we need to handle two types of events; blurs and submits.  And, as a brief side-note, why to bloggers, specifically technical bloggers, always say "we need" when outlining solutions.  Because, as we all know, solutions are a dime a dozen when it comes to this genre of work and if I know only one thing for certain, geeks will always out-geek each other (write that down… geek).  

So anyway, back to the nonsense.  The first loop attaches a function to each inputs blur event with calls our "to-be-yet-created" function "field_blur", which will handle the actual validation.  The submit event hook is self explanatory.  It does have an ugly redundant loop which forces validation on each input via it's blur event, but hey, that's life.

Step 3: Validate Inputs on Blur

var validators = Array('required', 'email', ... );
 var messages = { required : "You missed this one.  Oops!", ... }
 
 var field_blur = function(field) {
  $(field).blur(function() {
   error = "";
   
   // iterate through validator array looking for matching class
   for(i = 0; i < validators.length; i++) {
    if(error.length == 0) // check to make sure that only the first error is displayed
     if($(this).hasClass(validators[i])) // if element has validation class
      error = eval(validators[i] + "($(this)) ? messages." + validators[i] + " : ''"); // run validation
   }
   
   // if error found, insert in DOM
   if(error.length > 0)
    display_error($(this), error);
   else
    clear_error($(this));
  });
 }

Well, wasn't that pretty and did you notice the use of the infamous "eval" command?  Even Microsoft thinks so.  Obviously, this could be written far better, but the gist of it is simple: look for classes on each element that match a defined "validator" and then run the validatior's validation logic.

Conclusion

I love it when finishing a technical tutorial, the web author sums up the take-aways you were supposed to take-away.  As a contrarian thinker and a lazy one to boot, I'm going to leave that to you, my reader.  So, if you do find a take-away, please let me know.  Cheers!

Connect with us

Thank You!

We really appreciate your interest in what we do.

We'll get back to you as soon as we can.