Page 1 of 1

Form Validation - Logic of Required Fields

Posted: Mon Aug 29, 2005 11:26 pm
by CaptainMorgan
Hey folks,
For the past 2 1/2 weeks Ive been sincerely struggling with this and can't seem to work it out. Ive got everything else taken care of except for this one topic. I have a total of 10 fields with four fields I wish to have validated. The different sorts of validation I can enter at a later date for the last three of them. All I ask is that you please help me with or hint to me the validation necessary for one field... and Ill do the rest. The name or $visitor field, I figured if I can get human help for one, I shouldn't have a problem getting the others. The code is ALL on one page. It's processing everything correctly and exactly as I want it to. It is only not validating. I know it is a matter of logic, primarily in the if ($_POST['validate'] == 1) { block but I can't figure it out. I have about 20 other .php files that I have hacked to pieces with this one here the one that makes the most sense and actually works.

Code: Select all

<?php

    $visitor       = "";
	$business      = "";
	$state         = "";
	$country       = "";
	$visitor_email = "";
	$confirm_email = "";
	$phone         = "";
	$fax           = "";
    $message       = "";
	$file          = "";

    if ($_POST['validate'] == 1) {
	
		$visitor       = $_POST['visitor'];
		$name_error    = "Please enter your name";

		$business      = $_POST['business'];
		$state         = $_POST['state'];
		$country       = $_POST['country'];
		$visitor_email = $_POST['visitor_email'];
		$confirm_email = $_POST['confirm_email'];
		$phone         = $_POST['phone'];
		$fax           = $_POST['fax'];
		
		$message       = $_POST['message'];
		$message_error = "Please enter your message";
		
		$file          = $_POST['file'];
		
		$uploadDir  = 'upload';
		$uploadFile = $uploadDir . $_FILES['file']['name'];
			if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile))
				{              //return TRUE;//header ( "Location: /contact/contact_form_sent.htm" );
				
			//else
				//{return FALSE; //header ( "Location: /contact/contact_form_sent.htm" );
				 

		
		$recipient  = "myemail";
		$subject    = "Portfolio Website Submission Form";

		$message1  .= "E-mail: $visitor_email\nConfirm: $confirm_email\nSubject: $message_subject\n\nName: $visitor\nBusiness: $business\nState: $state\nCountry: $country\nEmail Preferred\nPhone: $phone\nFax: $fax\n\nComments: $comments\n\nIP: $ip\nAgent: $httpagent\nRef: $httpref\n\nFile: $file";
		$message2  .= "E-mail: $visitor_email\nConfirm: $confirm_email\nSubject: $message_subject\n\nName: $visitor\nBusiness: $business\nState: $state\nCountry: $country\nPhone Call Preferred\nPhone: $phone\nFax: $fax\n\nComments: $comments\n\nIP: $ip\nAgent: $httpagent\nRef:$httpref\n\nFile: $file";

		$headers    = "From: Portfolio\n";
		$headers   .= "Reply-To: $visitor_email";

        	if (($_POST['validate'] > 0) && (($contact == "Send-Email")) {
					mail($recipient,$subject,$message1,$headers);
					header ( "Location: /contact/contact_form_sent.htm" );
			} else {
					mail($recipient,$subject,$message2,$headers); 
					header ( "Location: /contact/contact_form_sent.htm" );
			}
		}
	}
?>
<html>........

A good portion is html of course and here is the beginning of the form and the first field:

Code: Select all

<form action="<?php echo $_SERVER['PHP_SELF']?>" id="contact_test" method="post" 
						enctype="multipart/form-data">
						<fieldset><legend>Demographic Information</legend>						
    
   					<div class="required">  
						<?php if ($visitor != "") {echo '<div class="error">'.$name_error.'</div>';} ?>      
				        <label for="visitor">Name:</label>
        					<input type="text" name="visitor" id="visitor" class="basictext" size="5" maxlength="50" 
								value="<? echo $name_error; ?>" />
							<input type="hidden" name="validate" value="1">
					</div>
......

I have bothered the IRC chaps beyond reproach and have got some nice fellows that have tried to help me but I fear I am helpless concerning this one topic. The validation. I can make it process, upload, make server requests and a bunch of other beginner php stuff without a hitch. I have run through more than a dozen tutorials and a dozen books and conducted countless searches over the past 2 weeks easily and simply cannot grasp this one concept. No book or tut has helped me solve this yet... I can't put the two and two together. I even worked up a story board in a text document:
I) Blank form√
Within PHP, fields are identified as blank $visitor=””; √

a) User enters input onto form
1) Form is submitted
Form must carry the values via $_POST

2) Form is validated
Tested – Email Syntax, Empty fields, Numbers only fields, Letters only fields

II) If validation is successful, form is sent to my email address with info
a) Redirected to congrats page
Header()

III) If validation is a failure, form is redisplayed
$_SERVER(“PHP_SELF”);

a) Previous successful and validated user input is retained and displayed
$_POST

b) Failed input is highlighted
CSS Layout with color, PHP test

IV) User enters correct fields
a) User resubmits the form
repeated

1) Form is checked again for validation
repeated

V) If success, form is submitted
Repeated

a) Redirected to congrats page
Repeated

VI) If fail, repeat procedure until successful validation
Repeated
Which did no good either.


I can write a one field validation form, no problem. But putting the four together is something Im desperate to learn. If not ultimate help, I would sincerely appreciate a hint or an instruction in the right direction.

Thank you

Posted: Tue Aug 30, 2005 2:03 am
by Burrito
what are you trying to validate? Whether or not the fields are populated? If they are populated with a specific type of data (ie date, email address, phone number etc)?


if the latter, you should check out the code snippets forum, d11wtq wrote a validation class a few months back that would probably suit your needs. If the former, just check the values of the posted data to ensure they are not empty:

ex:

Code: Select all

<?php
$validated = TRUE;
if(trim($_POST[field1]) == "")
  $validated = FALSE;
if(trim($_POST[field2]) == "")
  $validated = FALSE;
//etc.
if(!$validated)
{
    $msg = "something is wrong";
}
else
{
  // do your email and stuff here
}
?>
<html>
<body>
<?
if(isset($msg))
  echo $msg
?>
<form method="post">
<input type="text" name="field1" <? echo (isset($_POST['field1']) ? "value=\"".$_POST['field1']."\"" : "");?>>
<input type="text" name="field2" <? echo (isset($_POST['field2']) ? "value=\"".$_POST['field2']."\"" : "");?>>
<input type="submit" value="submit">
</form>
</body>
</html>

Posted: Tue Aug 30, 2005 2:19 am
by n00b Saibot
Burrito wrote:caveman, and also frozen
heh, heh, are you from ice-age :lol: you must have good amount of beard (in kms i think) :lol:

Posted: Tue Aug 30, 2005 11:15 pm
by CaptainMorgan
Burrito:

I appreciate the tips, thank you.

After checking out that thread you pointed to I did add some of what I could to my page but I can't make logical sense of what Ive done. Now, Im not getting any result except for a blank page with no error outputs.

From where I stand, it makes sense to me but I suck at this, obviously. I have adjusted a lot of it and have added a good amount of comments that should give an idea of what Im trying to accomplish.

What and where am I going wrong? I set the blank variables first.. then on validation the variables are retained; the four required fields have code applied to them, next, a file is uploaded and mail settings are set with a final code at the end based on two results of whether 1 of 2 radio checkboxes is checked.

I have tested everything and it has been a success up until I try setting the validation procedures; the four required fields.

I know I have the Name field incorrect. I thought I had the email set correctly because I tried to follow that class thread you mentioned. The message field seems okay because I got a return after positioning in differently but after further play with the Name and Email fields it no longer works.

Here is the full code with adjusted code and options State and Country in the html section cut out for conservation of space.

Code: Select all

<?php 
$ipi = $_SERVER['REMOTE_ADDR'];
$httprefi = $_SERVER['HTTP_REFERER'];
$httpagenti = $_SERVER['HTTP_USER_AGENT'];
?>
<?php

	/* Begin Blank Form Variables */
    $visitor       = "";
	$business      = "";
	$state         = "";
	$country       = "";
	$visitor_email = "";
	$confirm_email = "";
	$phone         = "";
	$fax           = "";
    $message       = "";
	$file          = "";

	/* Begin Validation and Redisplay Form if Necessary */
    if ($_POST['validate'] == 1) {
	
		/* Display Filled and Unfilled Fields */
		$business      = $_POST['business'];
		$state         = $_POST['state'];
		$country       = $_POST['country'];
		$phone         = $_POST['phone'];
		$fax           = $_POST['fax'];
		$file          = $_POST['file'];		
		
		/* Validate Name: Not Empty, First Character is a Capitalized Alpha, 
			& No Character is Numeric or a Symbol */
		$visitor       = $_POST['visitor'];
			if(trim($_POST[$visitor]) == "") {
    			$name_error     = "<div class='error'>Please enter your name</div>";
				 	}
					
		/* Validate 1st Email: Not Empty, Proper Format - email@email.com, Simply a
			Full Validation */
		$visitor_email = $_POST['visitor_email'];
		$email_error   = "<div class='error'>Please enter a valid email address</div>";
 			function validEmail($visitor_email) {	    
        		if (preg_match('/^[a-z0-9]+[\w\-_\.]*?[a-z0-9]@[a-z0-9]+[a-z0-9\-\.]*\.(?:com|uk|us|info|biz|gov|net|org|edu|ac|au|ca|de|eu|it|ro|ru|th)$/i', $visitor_email)) return true;
        			echo $email_error;
    			}
    	/* Validate 2nd Email: Not Empty, Matches 1st Email */
		$confirm_email = $_POST['confirm_email'];
		$confirm_error = "<div class='error'>Please be sure the addresses match</div>";
			if ($confirm_email == $visitor_email) {
				return true; 
			 } else {
			  		echo $confirm_error;
				  }
		
		/* Validate Message: Not Empty */ 
		$message       = $_POST['message'];
			if(trim($_POST[$message]) == "") {				
				$msg_error   = "<div class='error'>Please enter your message</div>"; 
					}

		} else {
				
		/* Begin File Uploading */
		$uploadDir 	   = 'user/upload';
		$uploadFile    = $uploadDir . $_FILES['file']['name'];
			if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile))
		
				{       
		
				/* Begin Outgoing Mail Settings */
				$recipient  = "myemail";
				$subject    = "Portfolio Website Submission Form";

				$message1  .= "E-mail: $visitor_email\nConfirm: $confirm_email\nSubject: $message_subject\n\nName: $visitor\nBusiness: $business\nState: $state\nCountry: $country\nEmail Preferred\nPhone: $phone\nFax: $fax\n\nComments: $comments\n\nIP: $ip\nAgent: $httpagent\nRef: $httpref\n\nFile: $file";
				$message2  .= "E-mail: $visitor_email\nConfirm: $confirm_email\nSubject: $message_subject\n\nName: $visitor\nBusiness: $business\nState: $state\nCountry: $country\nPhone Call Preferred\nPhone: $phone\nFax: $fax\n\nComments: $comments\n\nIP: $ip\nAgent: $httpagent\nRef:$httpref\n\nFile: $file";

				$headers    = "From: Portfolio\n";
				$headers   .= "Reply-To: $visitor_email";

			/* "How May I Contact You? - Email or Phone" Box */
        	if (($_POST['validate'] > 0) && ($contact == "Send-Email")) {
					mail($recipient,$subject,$message1,$headers);
					header ( "Location: contact_form_sent.htm" );
				} else {
					mail($recipient,$subject,$message2,$headers); 
					header ( "Location: contact_form_sent.htm" );
				}
			}
		}
	}
?> 
<!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>
<title>Contact Form</title>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
	<link rel="stylesheet" type="text/css" href="/styles/custom.css" />
	<link rel="stylesheet" type="text/css" href="/styles/form.css" />
	<link rel="stylesheet" type="text/css" href="/styles/form_input.css" />
	<script type="text/javascript" src="/scripts/fader.js"></script>
</head>

<body>
	<div id="container">
						
			<!-- Heading -->
			<div id="header">
				<h1>Portfolio</h1>
					<ul>
						<li><a href="/home" title="Home">Home</a></li>
						<li><a href="/about" title="About Me">About Me</a></li>
						<li><a href="/fun" title="Fun">Fun</a></li>
						<li><a href="/pictures" title="Pictures">Pictures</a></li>
						<li><a href="/links" title="Links">Links</a></li>
					</ul>
			</div>			
					
			<!-- Main Section -->
			<div id="main">
				<h2>If you want to contact me</h2>
					<p>(Bold fields are required.)</p>						  
						
					<!-- User Demographic Information -->
  					<form action="<?php echo $_SERVER['PHP_SELF']?>" id="contact_test" method="post" 
						enctype="multipart/form-data">
						<fieldset><legend>Demographic Information</legend>						
    
   					<div class="required">  
						<!--<if ($visitor != "") {echo '<div class="error">'.$name_error.'</div>';} ?> --> 
				        <label for="visitor">Name:</label>
						<? if(isset($name_error)) echo $name_error ?>
        					<!-- <input type="text" name="visitor" id="visitor" class="basictext" size="5" maxlength="50" 
								value="< echo $name_error; ?>" /> -->
							<input type="text" name="visitor" class="basictext" size="5" maxlength="50"
							<? echo (isset($_POST['visitor']) ? "value=\"".$_POST['visitor']."\"" : "");?>>
							<input type="hidden" name="validate" value="1">
					</div>
					
					<div class="optional">		
						<label for="business">Business:</label>
        					<input type="text" name="business" id="business" class="inputText" size="5" maxlength="50" value="" />
     			 	</div>
						
					<div class="optional">
        				<label for="state">State:</label>.....
        					
      				</div>
					
					<div class="optional">					
        				<label for="country">Country:</label>....
							
      				</div>
    					</fieldset>
						
						<!-- Contact Resources -->
    					<fieldset><legend>Contact Information</legend>
      				<div class="notes">
      				</div>
      
	  				<div class="optional">
        				<fieldset><legend>How May I Contact You?</legend>
          					<label for="contact_phone" class="labelRadio compact"><input type="radio" name="contact" 
							id="contact_phone" class="inputRadio" value="Phone-Call" /> Phone</label>
          					<label for="contact_email" class="labelRadio compact"><input type="radio" name="contact" 
							id="contact_email" class="inputRadio" value="Send-Email" checked="checked" /> Email</label>
        				</fieldset>
     			 	</div>
      
					<div class="required">
					 	<? if(isset($email_error)) echo $email_error ?>        
        				<label for="visitor_email">Email:</label>
        					<input type="text" name="visitor_email" id="visitor_email" class="inputText" size="10" maxlength="75" 
							<? echo (isset($_POST['visitor_email']) ? "value=\"".$_POST['visitor_email']."\"" : "");?> />
							<input type="hidden" name="validate" value="1">
        						<small>I will never sell or disclose your email address to anyone as I would not want 
								the same to happen to me.</small>
      				</div>
					
					<div class="required">
						<? if(isset($confirm_error)) echo $confirm_error ?>       
        				<label for="confirm_email">Re-enter Email:</label>
        					<input type="text" name="confirm_email" id="confirm_email" class="inputText" size="10" maxlength="75" 
							<? echo (isset($_POST['confirm_email']) ? "value=\"".$_POST['confirm_email']."\"" : "");?> />
							<input type="hidden" name="validate" value="1">
        						<small>Must match the email address you just entered above in the format: 
								<strong>name@domain.com</strong></small>
      				</div>
      
	  				<div class="optional">
        				<label for="phone">Phone:</label>
        					<input type="text" name="phone" id="phone" class="inputText" size="10" maxlength="30" value="" />
      				</div>
      
	  				<div class="optional">
        				<label for="fax">Fax:</label>
        					<input type="text" name="fax" id="fax" class="inputText" size="10" maxlength="30" value="" />
      				</div>
					
      				<div class="optional">
        				<fieldset><legend>Subject:</legend>
          				<label for="subject_educational" class="labelRadio"><input type="radio" name="message_subject" id="subject_educational" 
						class="inputRadio" value="Educational" /> Educational</label>
          				
						<label for="subject_business-professional" class="labelRadio"><input type="radio" name="message_subject" id="subject_business-professional" 
						class="inputRadio" value="Business-Professional" /> Business-Professional</label>         
						
						<label for="subject_employment-career" class="labelRadio"><input type="radio" name="message_subject" id="subject_employment-career" 
						class="inputRadio" value="Employment-Career" /> Employment-Career</label>
          				
						<label for="subject_personal" class="labelRadio"><input type="radio" name="message_subject" id="subject_personal" 
						class="inputRadio" value="Personal" /> Personal</label>
          				
						<label for="subject_other" class="labelRadio"><input type="radio" name="message_subject" id="subject_other" 
						class="inputRadio" value="Other" checked="checked"  /> Other</label>
        				</fieldset>
      				</div>
      					</fieldset> 
					
					<!-- Main Message -->
					<div class="required wide">
						<!-- if(isset($message)) echo $name_msg ?>-->
						<? if(isset($msg_error)) echo $msg_error ?>
        				<label for="message">Your Message:</label>
        					<textarea name="message" id="message" rows="10" cols="32"
							<? echo (isset($_POST['message']) ? "value=\"".$_POST['message']."\"" : "");?>></textarea>
							<input type="hidden" name="validate" value="1" />
						<br /><br />
					</div>
       				
					<div class="optional">
        				<label for="file">File:</label>
        				<input type="file" name="file" id="file" class="inputFile" />
        				<small>All files submitted are scanned for threats.</small>
						<br /><br />
    				</div>

					<!-- Cancel and Sumbit Buttons -->
    					<fieldset>
      				<div class="submit">
        				<div>
          				<input type="submit" class="inputSubmit" value="Send" />
          				<input type="submit" class="inputSubmit" value="Reset" />
        				</div>
      				</div>
    					</fieldset>
						<input type="hidden" name="ip" value="<?php echo $ipi ?>" />
						<input type="hidden" name="httpref" value="<?php echo $httprefi ?>" />
						<input type="hidden" name="httpagent" value="<?php echo $httpagenti ?>" />
					</form>
			</div>
									
			<!-- Right-Side Bar -->
			<div id="rightbar">
			<div class="section">			
				<h3><span>Menu</span></h3>
			</div>
						
			<div class="section">
			</div>
						
			<div class="section">							
					<ul>
						<li><a href="/" title="Back to Intro">Intro</a></li>
						<li><a href="/home" title="Home Page">Home</a></li>
						<li><a href="/about" title="About Me">About Me</a></li>
						<li><a href="/fun" title="Fun Stuff">Fun</a></li>
						<li><a href="/pictures" title="Pictures">Pictures</a></li>
						<li><a href="/links" title="Links and Other Info">Links</a></li>
					</ul>
				</div>
						
			<div class="section">
				<h3 id="links"><span>Other</span></h3>
					<ul>
						<li><a href='http://text' rel='text'>Text</a></li>
						<li><a href='http://text'>Text</a></li>
						<li><a href='http://text'>Text</a></li>
						<li><a href='http://text'>Text</a></li>
						<li><a href='http://text' rel='text'>Text</a></li>
						<li><a href='http://text'>Text</a></li>
						<li><a href='http://text'>Text</a></li>
					</ul>
					
				<div class="browsers">
					<a href="http://www.mozilla.org/products/firefox/" title="Get Firefox!">
					<img src="/images/getff.gif" id="GetFirefox" width="78" height="30" alt="Get FireFox!" /></a>
					<a href="http://www.opera.com/" title="Get Opera!"><img src="/images/getopera.gif" id="GetOpera"
					width="78" height="30" alt="Get Opera!" /></a>
				</div>					
			</div>
			</div>			
		
			<!-- Footer: Date - Long Format, Copyright and Validation -->
			<div id="footer">
			<div id="copyright">
					<b><script type="text/javascript" src="/scripts/date_longformat.js">
					</script><br />
					<script type="text/javascript">
						<!--//
							document.write(""+"Page Updated - "+document.lastModified + "");
						//-->
					</script>
					<br /> &copy; 2005 <span class="under">Validated:
					<a href="http://jigsaw.w3.org/css-validator/check/referer"> CSS</a></span> &<span class="under">
					<a href="http://validator.w3.org/check/referer">XHTML Strict</a></span></b>
			</div>
			</div>
			
	</div>
</body>
</html>

Thank you.