jQuery Validation – How to Use to Get Rid Of Even The Toughest Stains

So you want to use jQuery validation, huh?

What is it? Something that was added to the holy jquery site and is an easy way to validate input from users. Now this should in no way take over for server side validation, but it helps to at least catch a few things without having to send anything to the server. So how do ya do it?

Well to start, you need some files:

jquery-1.3.2.js and jquery.validate.js.

Now oddly enough the validation file isn’t hosted on the holy jquery site but how to use it is.

Ok now you have the files, what’s next? Well you need form, and I can do that for you.

So basically it’s a simple form with one input that is required.

jQuery(document).ready
    (
      function()
      {
        jQuery("#PrimaryForm").validate
        (
          {
            errorLabelContainer: "#ErrorDiv",
            wrapper: "div",
            rules:
            {
              FirstName :
              {
                required : true
              }
            },
            messages:
            {
              FirstName:
              {
                required : 'First Name is required.'
              }
            },
            onfocusout : false,
            onkeyup: false,
            submitHandler: function(label)
            {
              postSubmit();
            }
          }
        );
      }
jQuery("#PrimaryForm").validate

Real simple, just setting the validator to the primary form on the page.

 errorLabelContainer: "#ErrorDiv",

This sets the errors to show up in the ErrorDiv. Now this is optional, as you can have it show the errors next to the FirstName text box but personally I think that looks horrible. Setting up the ErrorDiv puts all the errors in one central location and allows for styling the actual div.

 rules:
 {
    FirstName :
    {
      required : true
    }
  },

This matches an element with the id of FirstName to the required rule, meaning that FirstName is required. Rocket science.

  messages:
  {
    FirstName:
    {
       required : 'First Name is required.'
    }
  },

If you can’t figure this out, I hear circus is hiring for the “World’s Dumbest Person”. You’ll fit in with Jub Jub the Dog Boy.

  onfocusout : false,
  onkeyup: false,

Basically this prevents the validation when leaving the textbox or on every key press. This is just another preference.

  submitHandler: function(label)
  {
    postSubmit();
  }

If the submit is successful, call this method.

But… BUT WHAT IF IT’S AN EMAIL?!??! WHAT WILL I DO???!?!?

Well for one, stop being such a child. And two, look here.

Some what different, as you can see it’s now email and there is one extra requirement in the rules:

  rules:
  {
    EmailAddress :
    {
      email : true,
      required : true
    }
  },
  messages:
  {
    EmailAddress:
    {
      required : 'Yo, email fool.',
      email : 'So not an email address.'
    },
  },

See? It has nice built in rule for email. Simple.

BUT WHAT IF I NEED A REGULAR EXPRESSION?!??! WHAT WILL I DO???!?!?

I swear if you don’t stop that, I’m turning this post around and going home.

Fine here it is.

  jQuery.validator.addMethod
  (
    "isZipCode",
    function(value, element)
    {
      return value.match(new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/));
    }
  );

Just have to create a method and “add it” to the validator itself. And then there’s the use:

  rules:
  {
    ZipCode :
    {
      required : true,
      isZipCode : true
    }
  },
  messages:
  {
    ZipCode:
    {
      required : 'For the love of me, enter a zip code!.',
      isZipCode : 'Serioulsy?  Do you know what a zip code is?'
    },
  },

Woo hoo right?

Don’t do it… Don’t you yell.

But what if one input depends on another?

Much better. Well that’s not as hard as it may seem and here’s the example.

  rules:
  {
    InputB :
    {
      required :
      {
        depends : function(element) { return jQuery('#InputA').val() != "" }
      }
    }
  },

As you can see, you can change how the required method works by adding in a depends handler. Works out pretty well.

Yes I will show you how to make sure two inputs match. I swear you ask for a lot.

  rules:
  {
    Password :
    {
      equalTo : "#ConfirmPassword"
    },
  },

Couldn’t be easier unless I wrote it out for you. Wait, I did.

So here you’ve either learned a bit about jQuery validation or have just spent the last few minutes drooling uncontrollably. Either way, I’m done with this post and you’re left to do whatever it is you do, you sick f—.

Side note: I haven’t actually been to Htmlgoodies since eh college? but wow did that place sell out. How fitting that an introduction to html page now looks like it was designed by someone just starting out… in the 90s.

7 thoughts on “jQuery Validation – How to Use to Get Rid Of Even The Toughest Stains”

  1. Hello,

    This article is very informative.

    I am a jquery newbie and still learning the ropes. I am using the Jquery validate.js plugin to validate a form and running into issues.
    I would greatly appreciate your help/input. Can you please help me resolve the issue.

    I have a form where elements can be added/removed dynamically and am having trouble validating the elements that are arrays.
    The validation works but the error message is being displayed for the “order_date” elements in all rows, even if they are valid.

    The form has two groups of radio buttons with names ( g1 and g2 ). It also has other elements like textboxes and select boxes.

    Buttons are defined as :

    Yes
    No

    Yes
    No

    div2 has elements like:

    div4 elements like:

    // returns true if the string is a valid date formatted as…
    // mm dd yyyy, mm/dd/yyyy, mm.dd.yyyy, mm-dd-yyyy
    function isDate(str){
    var re = /^(d{1,2})[s./-](d{1,2})[s./-](d{4})$/
    if (!re.test(str)) return false;
    var result = str.match(re);
    var m = parseInt(result[1]);
    var d = parseInt(result[2]);
    var y = parseInt(result[3]);
    var dateString = new Date(str);
    var today = new Date();
    if(dateString > today) return false;
    if(m 12 || y 2100) return false;
    if(m == 2){
    var days = ((y % 4) == 0) ? 29 : 28;
    }else if(m == 4 || m == 6 || m == 9 || m == 11){
    var days = 30;
    }else{
    var days = 31;
    }
    return (d >= 1 && d 0;
    },
    ‘Format: MM/DD/YYYY. No Future Dates’
    );

    $(document).ready(function() {
    $(“#myForm”).validate({
    rules: {
    “prodid[]”: {
    required: function(){
    return $(“input[name=g1][value=yes]:checked”).length > 0;
    }
    },

    “order_date[]”: {
    checkdate: true
    }
    }
    });
    });

    How do I make sure that the error message is displayed only for the invalid element?
    Also, Is there a method called “depends” in the validate plugin? If yes, can you please show me an example? I haven’t been able to find anything on the net.

    Appreciate your help and thanks in advance.

    Cheers,
    Mike.

  2. Please ignore my question about “depends”. I was too quick to post that. This article itself has an example using “depends”.

    Mike.

Comments are closed.