Validating forms with JQuery Validation: Ensuring at least one checkbox is checked

On occasion, you’re going to have some mammoth form that doesn’t validate properly with any Javascript validation library.   One event is when the form you are given to deploy has a lot of checkboxes and one of those checkboxes needs to be checked to be valid.  The easiest way to make sure this happens is to create a form submission even listener then if there’s at least one checkbox checked, it returns true at which time it triggers the form validation OR it sends the “e.preventDefault()” command, which will stop any further processes, in this case, triggering the form submission which would then trigger the validation.  It’s kind of pre-submit validation, but to me, it’s the fastest way to “piggyback” on the existing form validation if everything else works properly.

Here is a sample, and this is the form library that I think is incredibly reliable, clean, and very easy to use:

http://jqueryvalidation.org/documentation/

$("#mainForm").on('submit',function(e){

   if ( $("input[type='checkbox']:checked").length > 0) {


   }
   else {
         e.preventDefault();

         alert("Please check at least one category you wish to be listed in.");
         return false;
   }

   return true;

});


$("#mainForm").validate();

This works well CDN’d with Symfony form projects.

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *