Example implementation of jQuery Validation plugin

The jQuery validation plugin is an excellent tool for validating forms. The online documentation is actually quite extensive, but I found it difficult to locate any example code that really showed a full implementation of the plugin with all of its methods. After a lot of collaborative work, I've written an implementation of this plugin that manages to use most of the of customizable methods. There's a bit of my own jQuery thrown in this, but it should help to provide others with a good working model that can easily be reverse-engineered.

 <script type="text/javascript" src="/templates/func/jquery.validate.js"></script>
 <script>
  var cgre = "Required"; //define alternate error message for required fields
 
  jQuery(document).ready(function(){
 
    //format inputs
    jQuery('input[type="radio"]').addClass('radio-input');
    jQuery('input').wrap('<span class="input-wrapper" />');
 
    /* **
    /*  FORM VALIDATION
     */
 
    //define a new validation method for prepopulated fields-- make sure that they haven't been left with default values. this works in tandem with check for 'required' class
    jQuery.validator.addMethod("prepopulatedVal", 
 
      function(value, element, param) {
       if(jQuery(param).length == 1) {
          return value != jQuery(element).attr('rel'); //does it have its default value?
       } else {
        return true;
       }
      },"Please fill out this field."
 
    ); 
 
    jQuery("#myform").validate({
     //set custom placement of error messages. do not modify css information here (do that in the 'highlight' method), only placement.
      errorPlacement: function(error, element) {
 
        if ( element.is(":radio") ){
          error.insertBefore( element.parents('.radio-wrapper') );       
        }
        else if ( element.is(":checkbox") ){
          error.insertBefore( element.parent().children('input:first') );        
        }
        else if ( element.is("textarea")){
          error.insertBefore ( element );    
        }
        else {
          error.appendTo( element.parent() );
        }
      },
      //set custom error messages
      invalidHandler: function(e, validator) {
        var errors = validator.numberOfInvalids();
        if (errors) {
          var message = errors == 1
            ? 'One required field was left empty. Please complete the highlighted required field, and then click on Submit.'
            : '' + errors + ' fields were left empty. Please complete the highlighted required fields, and then click on Submit.';
 
          alert(message);
        }
      },
 
 
      //define dependency and requirement rules
      rules: {
 
        media_name: {                   
          prepopulatedVal: '#fee_status_media:checked' //run 'prepopulatedVal' method on media_name only if fee_status_media is checked
        },       
        contact_email: {          
          email: true
        },      
        preferred_format: {
          required: '#have_preferred_format_yes:checked'
        },   
        preferred_other: {
          required: '#preferred_format_other:checked'
        }, 
        explain_contents: {
          maxlength: 3000
        },
        disseminate_to_whom: {
          maxlength: 3000
        }
 
      },
 
      //modify error message for specific input fields
      messages: {
        contact_name: {
          required: cgre //display cgre error message is 'required' validation fails
          //cgre was variable defined earlier as "Required"
        },
        contact_street: {
          required: cgre
        },
        media_name: {
          prepopulatedVal: ''  //display no error message is 'prepoulatedVal' validation fails
        }
 
      },
 
      //modify input appearance for fields that have failed validation
      highlight: function(element, errorClass, validClass) {
 
        //specific styling for radio inputs
        if ( jQuery(element).is(":radio") ){        
          jQuery('label[for="' + jQuery(element).attr('name') + '"]').addClass('radio-error');   //this will apply the style to all radio inputs that have the same name
          jQuery('input[name="'+jQuery(element).attr('name')+']"').parents('.radio-wrapper').addClass('error-wrapper');        
        }
        //default functionality
        jQuery(element).addClass(errorClass).removeClass(validClass);
      },
 
      //reverse modifications to input appearance for fields that have failed validation
      unhighlight: function(element, errorClass, validClass) {
 
        if ( jQuery(element).is(":radio") ){
          jQuery('input[name="'+jQuery(element).attr('name')+'"]').parents('.radio-wrapper').removeClass('error-wrapper');
        }
 
        //default functionality
        jQuery(element).removeClass(errorClass).addClass(validClass); 
      }    
      //,debug: true //prevents form from actually being submitted
 
    });
 
 
    /* **
    /* END FORM VALIDATION
     */
 
    //force validation to occur whenever fee_status is changed. I've added this here because media_name relies on fee_status for validation, and I want them to be validated together and on-the-fly
    jQuery('input[name="fee_status"]').click(function(){
        jQuery('input[name="media_name"]').valid();
    });
 
 
    /* **
    /* PREPOPULATE FIELDS
     */  
 
    //prepopulate fields that need default values (using rel attribute)
    jQuery('.prepopulate').each(function(){
      jQuery(this).val( jQuery(this).attr('rel') );
    });
 
    //clear default value on click
    jQuery('.prepopulate').focus( function(){
      if( jQuery(this).val() == jQuery(this).attr('rel') ){
        jQuery(this).val(''); 
      }
    });   
 
    //restore default value if field is left blank after click
    jQuery('.prepopulate').blur(function(){
      if( jQuery(this).val() =='' ){
        jQuery(this).val( jQuery(this).attr('rel') ); 
        jQuery(this).valid(); //check validation on this field on blur
      }
    });
 
    /* **
    /* END PREPOPULATE FIELDS
     */      
 
 
  });  
</script>

Comments

This is an awesome example. I agree - the jQuery validation plugin you are referring to has an extensive API, and while there is documentation, it is difficult to comprehend at times, given the complexity of the domain.

Thanks, still very usefult

So Cool, It is very nice.

Hi, First off, thanks a ton for this tutorial! Works like a charm. I am usign field group's multipage settings with the save button at the end of the multipage group. So clicking save validates only the final multipage and not the others. Is there anyway out of this?
Thanks a ton
Jaya

I really like your forum here. So I decided to be a part of it :)

And here I am saying HELLO EVERYBODY!! :D

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.