Solved

Dynamic JQuery Validation based on selected items on form

Posted on 2009-07-06
7
2,357 Views
Last Modified: 2012-06-27
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/
0
Comment
Question by:polobruce
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 82

Expert Comment

by:hielo
ID: 24789732



<!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
 

Author Comment

by:polobruce
ID: 24794439
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
 
LVL 82

Expert Comment

by:hielo
ID: 24794522
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:polobruce
ID: 24795716
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
 
LVL 82

Accepted Solution

by:
hielo earned 500 total points
ID: 24798102
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
 
LVL 82

Expert Comment

by:hielo
ID: 24798413
>>Also, you need to call this:
I meant to write:

"Also, you  NOT need to call this:"
0
 

Author Closing Comment

by:polobruce
ID: 31600337
THANK YOU SO MUCH!!!!! It working great now!

0

Featured Post

Certified OpenStack Administrator Course

We just refreshed our COA course based on the Newton exam.  With 14 labs, this course goes over the different OpenStack services that are part of the certification: Dashboard, Identity Service, Image Service, Networking, Compute, Object Storage, Block Storage, and Orchestration.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

627 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question