Adding a switch statement to a validation script

I’m trying to figure out how to validate a form that changes depending on which selection you make.
here is the form:

basically there is a drop down and when the user makes a selection i’m using query to place a specific form for that selection. Most of the fields are the same for each form so I put the duplicates in 2 php files(base_top.php and base_bottom.php) and include them in with a php include statement. for example on the general form (which has the least form specific fields) this is the file:



<script>
        $(document).ready(function() {
            $( "#datepicker" ).datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'mm-dd-yy',  
            });

        });
</script>

 <h1>General Request</h1>
<!-- This is the liquid planner email address for the project folder -->
<input type="hidden" name="project" value="6197590-b88873b6803c422c@in.liquidplanner.com">
<!-- This is the request_type for the switch statement -->
<input type="hidden" name="request_type" value="general.php">


<!-- ====================================================================================-->
<!-- ====================   General Fields on all forms    ==============================-->
<!-- ====================================================================================-->


    <?php include "base_top.php";?>


<!-- ====================================================================================-->
<!-- ===========================   Request Specific Fields   ==============================-->
<!-- ====================================================================================-->

<!-- Checkbox -->

<div class="control-group">
  <label class="control-label" for="audience">Please select the audience for this project (Select all that apply)</label>
  <div class="controls">
    <input type="checkbox" name="audience[]" value="Current Students">Current Students<br>
    <input type="checkbox" name="audience[]" value="Alumni">Alumni<br>
    <input type="checkbox" name="audience[]" value="Business">Business<br>
    <input type="checkbox" name="audience[]" value="Faculty">Faculty<br>
    <input type="checkbox" name="audience[]" value="Prospective Students">Prospective Students<br>
    <input type="checkbox" name="audience[]" value="Community">Community<br>
    <input type="checkbox" name="audience[]" value="Donors">Donors<br>
    <input type="checkbox" name="audience[]" value="Local Businesses">Local Businesses<br>
    <input type="checkbox" name="audience[]" value="Other">Other
    <input type="text" name="audience_other" placeholder="other audiences" style="width:300px"/><br>
  </div><!-- close controls -->
</div> <!-- close control group -->

 <!-- TEXT INPUT -->
  <div class="control-group">
    <label class="control-label" for="completion_date">Request Completion Date:</label>
    <div class="controls">
      <input type="text" class="input-xlarge" name="completion_date" id="datepicker" placeholder="01/05/2013">
    </div> <!-- close controls -->
  </div><!-- close control group -->



<!-- ====================================================================================-->
<!-- ====================   General Fields on all forms    ==============================-->
<!-- ====================================================================================-->


    <?php include "base_bottom.php";?>

Here is the index.php file where the above form gets put.


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    
    <title>Marketing Request</title>
    <!-- <link rel="stylesheet" media="screen" href="css/form.css" > -->
    <link href="css/validate.css" rel="stylesheet">

    <script type="text/javascript">
    window.onload = function() {
        var arrInputs = document.getElementsByTagName("input");
        for (var i = 0; i < arrInputs.length; i++) {
            var curInput = arrInputs[i];
            if (!curInput.type || curInput.type == "" || curInput.type == "text")
                HandlePlaceholder(curInput);
        }
    };

    function HandlePlaceholder(oTextbox) {
        if (typeof oTextbox.placeholder == "undefined") {
            var curPlaceholder = oTextbox.getAttribute("placeholder");
            if (curPlaceholder && curPlaceholder.length > 0) {
                oTextbox.value = curPlaceholder;
                oTextbox.setAttribute("old_color", oTextbox.style.color);
                oTextbox.style.color = "#c0c0c0";
                oTextbox.onfocus = function() {
                    this.style.color = this.getAttribute("old_color");
                    if (this.value === curPlaceholder)
                        this.value = "";
                };
                oTextbox.onblur = function() {
                    if (this.value === "") {
                        this.style.color = "#c0c0c0";
                        this.value = curPlaceholder;
                    }
                };
            }
        }
    }
    </script>

    <link rel="stylesheet" href="themes/base/jquery.ui.all.css">
    <script src="js/jquery-1.7.2.js"></script>
    <script src="ui/jquery.ui.core.js"></script>
    <script src="ui/jquery.ui.widget.js"></script>
    <script src="ui/jquery.ui.datepicker.js"></script>
    <!-- <link rel="stylesheet" href="../demos.css"> -->
   
    <script type="text/javascript">

        $(document).ready(function(){
         
            $('.element').change(function() {   
                var qString = 'requests/' + $('#request_type').val();
                
                // if request is default value refresh page
                if ($('#request_type').val() == 0){

                    // refresh page
                    //alert(qString);
                    window.location.reload()
                }
                else{

                    //alert(qString);
                    $('#specific_request_type').load(qString);
                }
                

           }); // end .element').change(function()

            $('.element1').click(function() {   
                var qString = 'requests/' + $(this).attr("id");
                
                // if request is default value refresh page
                //alert(qString);
                $('#specific_request_type').load(qString);
                
              }); // end .element').clikc(function()

              $('.element1').css( 'cursor', 'pointer' );



        }); // end doc.ready

    </script>
</head>

<body>

<div class="container">

       <div class="page-header">
            <h1>Marketing Request Form</h1>
            <p>All order for items needed by the end of the fiscal year need to be placed before July 31st</p>
        </div>

<div class="row">
    <div class="span12">
    <form action="scripts/proc_form.php" id="contact-form" class="form-horizontal" enctype="multipart/form-data">
    

        <input type="hidden" name="uploadtoken" value="<?= $upload_token ?>" />
        <input type="hidden" name="callback" value="<?= $callback_url ?>" />

         <!-- select - drop down -->
        <div class="control-group">
          <label class="control-label" for="request_type">Make Selection</label>
          <div class="controls">
            <select name="request_type" id="request_type" class="input-xlarge element" >
                <option value="">Select Request Type</option>
                <option value="eventSupport.php">Event Support</option>
                <option value="webRequest.php">Website Revisions &amp; Updates, Landing Pages &amp; Email</option>
                <option value="collateral.php">Print Collateral</option>
                <option value="promo.php">Promo Items</option>
                <option value="sponsorships.php">Sponsorships</option>
                <option value="press.php">Press Release</option>
                <option value="communication.php">Communication Plan</option>
                <option value="social_media.php">Social Media</option>
                <option value="letterhead.php">Letterhead</option>
                <option value="general.php">Other/General</option>        
            </select>
          </div><!-- close controls -->
        </div> <!-- close control group -->

       
        <div id='specific_request_type'> </div> <!-- close specific_request_type -->


      
   </form>

   </div><!-- .row -->
</div> <!-- .container -->

<!-- JQuery and other scrupots for the file upload api -->

<!-- ==============================================
         JavaScript below!  -->                                                     

<!-- jQuery via Google + local fallback, see h5bp.com -->
     

<!-- Validate plugin -->
      <script src="js/jquery.validate.min.js"></script>
    
<!-- Scripts specific to this page -->
       <script src="js/lp_form_base.js"></script>
</body>
</html>

So my question is how do I handle validating the forms with all of these options? On the server side (php) i’m checking all of the fields that are the same throuout and then using a switch statement based off of the value in the first drop down which triggers the custom forms. Should I use the same technique with jquery? If yes can I get some help with the syntax? The value of request_type will tell me which form was selected. Here is my current validation script which works for the “general” form:


$(document).ready(function(){

      $('#contact-form').validate({
	    rules: {
	      
	      task_name: {
	        minlength: 2,
	        required: true
	      },

	      request_desc: {
	        minlength: 2,
	        required: true
	      },

	      goal: {
	        minlength: 2,
	        required: true
	      },

	      support_location: {
	        minlength: 2,
	        required: true
	      },

	      requester_name: {
	        minlength: 2,
	        required: true
	      },
	      
	      requester_email: {
	        required: true,
	        email: true
	      },
	      
	      requester_depart: {
	        required: true
	      },

	      approval_name: {
	        minlength: 2,
	        required: true
	      },
	      
	      approval_email: {
	        required: true,
	        email: true
	      },
      
	    },
	    messages: { 
            task_name: "Enter a task name",

            request_desc: "Enter a task description",

            goal: "Enter the goal of task",

            support_location: "Enter locations supporting request",

            requester_name: "Enter a Task Name",

            approval_name: "Enter a Task Name",

       		requester_email: { 
                required: "Please enter a valid email address", 
                minlength: "Please enter a valid email address", 
                remote: jQuery.format("{0} is already in use") 
            },

            approval_email: { 
                required: "Please enter a valid email address", 
                minlength: "Please enter a valid email address", 
                remote: jQuery.format("{0} is already in use") 
            },    
            
        },
	    highlight: function(label) {
	    	$(label).closest('.control-group').addClass('error');
	    },
	    success: function(label) {
	    	label
	    		.text('OK!').addClass('valid')
	    		.closest('.control-group').addClass('success');
	    }
	     
	  });
	  
}); // end document.ready

note- i’m in the process of changing all of the format of the form to use a twitter bootstrap / query validation demo I found and only the “other/general” fields have been converted over so you might see some fields inside of a list and others inside of divs

I have tried this but I get errors. I can’t figure out how to add a switch to the validate function.


$('#contact-form').validate({
	
	    switch (request_type){

	      	case 'general.php':
	      		
			   rules: {
			
			      task_name: {
			        minlength: 2,
			        required: true
			      },

			      request_desc: {
			        minlength: 2,
			        required: true
			      },

			      goal: {
			        minlength: 2,
			        required: true
			      },

			      support_location: {
			        minlength: 2,
			        required: true
			      },

			      requester_name: {
			        minlength: 2,
			        required: true
			      },
			
			      requester_email: {
			        required: true,
			        email: true
			      },
			
			      requester_depart: {
			        required: true
			      },

			      approval_name: {
			        minlength: 2,
			        required: true
			      },
			
			      approval_email: {
			        required: true,
			        email: true
			      },
		
			    },
			    messages: {
		            task_name: "Enter a task name",

		            request_desc: "Enter a task description",

		            goal: "Enter the goal of task",

		            support_location: "Enter locations supporting request",

		            requester_name: "Enter a Task Name",

		            approval_name: "Enter a Task Name",

		       		requester_email: {
		                required: "Please enter a valid email address",
		                minlength: "Please enter a valid email address",
		                remote: jQuery.format("{0} is already in use")
		            },

		            approval_email: {
		                required: "Please enter a valid email address",
		                minlength: "Please enter a valid email address",
		                remote: jQuery.format("{0} is already in use")
		            },

	      	break;

	      	case 'letterhead.php':
	      	
	      	// validate something
	      	break;

	      },
	

        },
	    highlight: function(label) {
	    	$(label).closest('.control-group').addClass('error');
	    },
	    success: function(label) {
	    	label
	    		.text('OK!').addClass('valid')
	    		.closest('.control-group').addClass('success');
	    }
	
	  });

You can’t use a switch statement in the validate object - it’s just object definitions that are allowed in there.

You’re saying that “The value of request_type will tell me which form was selected.”

When that select option changes, you can remove the existing form validation rules and use the value of the option to decide on which new set of validation rules to apply.

For example:


$('#request_type').on('change', function () {
    // remove existing rules
    $('input, select, textarea').each(function() {
        $(this).rules('remove');
    });

    // apply new validation rules
    switch (this) {
    case 'general.php':
        $(this.form).validate({
            rules: {
                task_name: {
                    minlength: 2,
                    required: true
                },
                ...
            }
        });
        break;
    case 'eventSupport.php':
        ...
        break;
    default:
        // do nothing
    }
});

Something like that.