Dynamic JQuery Validation based on selected items on form

I am using the jQuery inline form validation plugin below.  But I need to be able to dynamically change what fields are required based on various selections on a form.  

A basic example would be I have a dropdown and the person has to select their payment method.  How do I make the credit card fields validate if a credit card was selected as payment type but not if for example a field has a zero in it (i.e. no payment due) or if they selected check or invoice me from the drop down.



http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
polobruceAsked:
Who is Participating?
 
hieloCommented:
in your plugin, look for this:
$("form").bind("submit", function(caller){   // ON FORM SUBMIT, CONTROL AJAX FUNCTION IF SPECIFIED ON DOCUMENT READY
 
		if(submitValidation(this) == false){
 
 
and replace it with this:
$("form").bind("submit", function(caller){   // ON FORM SUBMIT, CONTROL AJAX FUNCTION IF SPECIFIED ON DOCUMENT READY
$(".formError").remove();
		if(submitValidation(this) == false){
 
 
Also, you need to call this:
 jQuery("[class^=validate]").validationEngine({
      success :  false,
      failure : function() {}
      });
 
 
again. Simply use:
<script language="JavaScript" type="text/javascript">
<!--
function validatePayment(payment)
{
	//alert('starting the validation process');
	var paymenttype = jQuery("#paymenttype").val();
 
	//detect the payment type
	if( paymenttype=="credit_card" )
	{
		$("#cc").addClass("validate[required]");
		$("#fullname").addClass("validate[required]");
	}
	else if( paymenttype=="cheque" )
	{
		$("#cc").removeClass("validate[required]");
		$("#fullname").removeClass("validate[required]");
	}
 
}
//-->
</script>

Open in new window

0
 
hieloCommented:



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 
<html>
<head>
<title>Untitled</title>
<script language="JavaScript" type="text/javascript">
<!--
function validatePayment(payment)
{	//detect the payment type
	if( payment=="credit_card" )
	{
		// assign the relevant validation for each of the elements within the containing div
		$("#fullname").addClass("validate[required]");
		$("#cc").addClass("validate[required,onlyNumber]");
	}
	else if( payment=="cheque" )
	{
		//same logic as the "if" clause above
	}
 
 
	//now force the engine to rescan the page for elements that have "validate" in the class
      $("[class^=validate]").validationEngine({
      success :  false,
      failure : function() { callFailFunction()  }
      });
 
}
//-->
</script>
 
</head>
<body>
<select onchange="validatePayment">
	<option value="">make a selection</option>
	<option value="credit_card">Credit Card</option>
	<option value="cheque">Cheque</option>
</select>
<div id="credit_card">
	<input type="text" name="fullname" id="fullname" value="" />
	<input type="text" name="cc" id="cc" value="" />
</div>
</body>
</html>

Open in new window

0
 
polobruceAuthor Commented:
Thanks for the reply.  Ok so I had to make a few changes to the code you provided to get it to execute but i'm still having some issues.  I've attached my page so you can see what i've done.

So here's the issues.

I select credit card, don't fill any fields in and then hit submit.   The 3 fields that are required show correctly that they are required.

Then I select Check and hit submit.   It then shows correctly that only the 3rd field is required (this is a hard coded validation in that field).  

I then switch it back to credit card and hit submit and it still only thinks the 3rd field is required.

Now i'm not sure if this is correct, but in order to get the check validation to turn off the cc and fullname required validation I had to removeclass and then addclass with a validation optional flag.  For some reason if I didn't have that it wouldn't work and I would get a javascript error.  But with doing that it seems to work. .  Now, i've tried adding that same removeclass addclass type of code in the credit_card validation and it appears to require the fields, but only shows the bubble required text for the second and third fields.


Any ideas on how to resolve this?

Also, anyway that I can get the required field text removed if for example it was originally required and fields not filled out, but then when changing the value of the drop down they are no longer required.  Currently you have to tab into those fields to remove the required text.

Example: Select Credit Card, Submit, All fields show required.  Change dropdown to Check hit submit.  All fields still show required text.  Tab into first field and required text is removed.  Tab into second, text is removed.


Thanks!
I also would like to figure
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
		<title>TopCon Registration</title>
		<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" title="no title" charset="utf-8" />
		<link rel="stylesheet" href="css/template.css" type="text/css" media="screen" title="no title" charset="utf-8" />
		
<script type='text/javascript' src='js/jquery.js'></script>
 
	
	
			
        
		<cfinclude template="/assets/javascripts/greybox/greybox.cfm">
        
 
    <!---
<script type="text/javascript">
document.getElementById("paymentinfo").style.display="block";
</script>
--->
    
	</head>
 
<body>
 
<script src='js/jquery.validationEngine.js' type='text/javascript'></script>
 
 
<script language="JavaScript" type="text/javascript">
<!--
function validatePayment(payment)
{       
//alert('starting the validation process');
var paymenttype = jQuery("#paymenttype").val();
//detect the payment type
        if( paymenttype=="credit_card" )
        {
			
                // assign the relevant validation for each of the elements within the containing div
				//jQuery("#fullname").removeClass();
				jQuery("#cc").addClass("validate[required]");
                jQuery("#fullname").addClass("validate[required]");
               
        }
        else if( paymenttype=="cheque" )
        {
		
				//alert('check please');
 
				jQuery("#fullname").removeClass();
                jQuery("#cc").removeClass();
                
				jQuery("#fullname").addClass("validate[optional]");
                jQuery("#cc").addClass("validate[optional]");
                //same logic as the "if" clause above
		        }
 
 
 
 
        
      jQuery("[class^=validate]").validationEngine({
      success :  false,
      failure : function() {}
      });
 
}
//-->
</script>
 
<form name="test" id="test" method="post">
 
<select name="paymenttype" id="paymenttype" onchange="validatePayment();">
        <option value="">make a selection</option>
        <option value="credit_card">Credit Card</option>
        <option value="cheque">Cheque</option>
</select>
<div id="credit_card">
        <input type="text" name="fullname" id="fullname" value="" />
        <input type="text" name="cc" id="cc" value="" />
</div>
 
<input type="text" name="bruce" id="bruce" class="validate[required]" value="" />
 
<input type="submit" name="submit" value="submit" />
 
</form>
 
 
</body>
</html>

Open in new window

0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
hieloCommented:
I don't have that plugin installed, but I see you have:
 jQuery("#cc").removeClass();


If you dynamically added a class:
jQuery("#cc").addClass("validate[required]");


then, you should be removing only the class you added dynamically:
jQuery("#cc").removeClass("validate[required]");


NOT
jQuery("#cc").removeClass();
0
 
polobruceAuthor Commented:
Hielo,

I had tried removing just the class that I added, but then the issue becomes what class is the field currently set to.  i.e. is it blank.  is it validate optional or is it validate required.  

So I thought I would remove all classes for the field and reset them since specifying a class is an optional argument.

Thoughts?
0
 
hieloCommented:
>>Also, you need to call this:
I meant to write:

"Also, you  NOT need to call this:"
0
 
polobruceAuthor Commented:
THANK YOU SO MUCH!!!!! It working great now!

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.