We help IT Professionals succeed at work.

PHP Contact Form Validation

motolanix1
motolanix1 used Ask the Experts™
on
Hi Experts,

I have a basic HTML form (contact form.html) and a php page (mail.php). When the user clicks submit, rather than the errors and message being displayed on another page, I want the errors displayed on one page under the form field or on top of the form. Therefore I would have one page contact.php.

The validation will be on the users name, email address and message. I have attached the 2 pages.

Speedy response is very much appreciated.
contactform.html
mail.php
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hello,

First the HTML form action parameter will point to itself, or in this case, leave it blank so that it posts to itself:
<form action="" method="post">
</form>

Open in new window


Then at the top of your contact.php form page, before any output is generated, put your form validation code.  You can use an IF statement for this.
<?php

if($_POST["Submit"]):
  # process form validation code
  $errorlist = "";
  $errorcount = 0;

  if(!$_POST["field1"]):
      $errorlist .= "<p>Please enter value for field 1</p>";
      $errorcount++;  
  endif;

  #repeat for other fields

  if($errorcount == 0):
       #process form and redirect to confirmation page  
       die(header("Location: confirm.php"));
  endif;

endif;
   
        #display errors
        echo $errorlist;
        #display HTML form
   
?>

Open in new window


I might have a typo or two but this should get your started.
Mark BradyPrincipal Data Engineer

Commented:
You could also check the input with javascript. Give your form an id field and value like this

<form id='myform' method='post'>

This will check there is values in the fields you need values in before submitting the form. Basically you have a function like this

function checkForm() {
// check fields here
if(document.getElementById('name') == '') {
    alert('Please enter your name!');
    exit();
}
// etc.. with the other fields you need.
// If they are all filled in the code will continue
document.myform.submit();
}

In your form you will need to add id fields to the form elements. For example the name field would be

<input type='text' id='name' value=''>

Now the function can check if it is empty. If any field you specify is not filled in, the form will not be submitted at all and the user will get a pop up alert. This saves the form data from being sent until it is all filled in or as you want it and the error alerts happen instantly as it is running on the users computer not being interpreted by the server and sending a message back.

To be honest, I check my forms both with javascript AND with php once it gets sent just in case the user turns off js.

Author

Commented:
Hi Expert, I am happy with answer. A little help. I have provided my code below but nothing appears as the page is blank. Can you help?


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php
if(isset($_POST['email'])) {
     
    // CHANGE THE TWO LINES BELOW
    $email_to = "tom@hotmail.com";
     
    $email_subject = "Website Inquiry Request";
     
     
    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.<br /><br />";
        echo $error."<br /><br />";
        echo "Please go back and fix these errors.<br /><br />";
        die();
    }
     
    // validation expected data exists
    if(!isset($_POST['first_name']) ||
        !isset($_POST['last_name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['telephone']) ||
        !isset($_POST['comments'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');      
    }
     
    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required
     
    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
  }
    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.<br />';
  }
  if(!preg_match($string_exp,$last_name)) {
    $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
  }
  if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.<br />';
  }
  if(strlen($error_message) > 0) {
    died($error_message);
  }
    $email_message = "Form details below.\n\n";
     
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
     
    $email_message .= "First Name: ".clean_string($first_name)."\n";
    $email_message .= "Last Name: ".clean_string($last_name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Telephone: ".clean_string($telephone)."\n";
    $email_message .= "Comments: ".clean_string($comments)."\n";
     
     
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);  
?>
 
<!-- place your own success html below -->
 
Thank you for contacting us. We will be in touch with you very soon.
 
<?php
}
die();
?>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>..:: Contact ::..</title>
</head>

<body>
<form name="htmlform" method="post" action="">
<table width="650px" height="400px">
</tr>
<tr>
 <td valign="top">
  <label for="first_name">Your Name <span class="asterix">*</span></label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input  type="text" name="first_name" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="50" size="35">
 </div>
 </td>
</tr>
 
<tr>
 <td valign="top"">
  <label for="last_name">Company Name</label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input type="text" name="last_name" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="50" size="35">
  </div>
 </td>
</tr>
<tr>
 <td valign="top">
  <label for="email">Email Address <span class="asterix">*</span></label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input type="text" name="email" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="80" size="35">
 </div>
 </td>
 
</tr>
<tr>
 <td valign="top">
  <label for="telephone">Telephone Number</label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input type="text" name="telephone" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="30" size="35">
  </div>
 </td>
</tr>
<tr>
 <td valign="top">
  <label for="comments">Message <span class="asterix">*</span></label>
 </td>
 <td valign="top">
 <div class="text_field_ta">
  <textarea name="comments" maxlength="1000" style=" border:none; width:460px; margin-top:3px; margin-left:3px;" cols="61" rows="12"></textarea>
 </div>
 </td>
 
</tr>
<tr>
<td></td>
 <td align="left" valign="middle">
 <input name="Submit" type="submit" class="send_c" value="Send Enquiry" />
 </td>
 </td>
</tr>
</table>
</form>

</body>
</html>

Author

Commented:
Can you see what could be wrong?
Sure.  I changed a couple things.  First the form processing should be done before any output is displayed, so the DOCTYPE line was moved down after the IF statement.  Also, the reason the page was blank was due to the die() being placed after the bracket instead of before.  I changed this as well.  Lastly, I typically check for if the submit button is pressed when form validating so instead of starting with IF the email field has a value, I changed it to if the submit button has a value.  I tested this and it works.

<?php	
	if(isset($_POST['Submit'])) {
     
		// CHANGE THE TWO LINES BELOW
		$email_to = "tom@hotmail.com";
		$email_subject = "Website Inquiry Request";
     
		function died($error) {
			// your error code can go here
			echo "We are very sorry, but there were error(s) found with the form you submitted. ";
			echo "These errors appear below.<br /><br />";
			echo $error."<br /><br />";
			echo "Please go back and fix these errors.<br /><br />";
			die();
		}
     
		// validation expected data exists
		if(!isset($_POST['first_name']) ||
			!isset($_POST['last_name']) ||
			!isset($_POST['email']) ||
			!isset($_POST['telephone']) ||
			!isset($_POST['comments'])) {
			died('We are sorry, but there appears to be a problem with the form you submitted.');      
		}
     
		$first_name = $_POST['first_name']; // required
		$last_name = $_POST['last_name']; // required
		$email_from = $_POST['email']; // required
		$telephone = $_POST['telephone']; // not required
		$comments = $_POST['comments']; // required
     
		$error_message = "";
		$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  
		if(!preg_match($email_exp,$email_from)) {
		$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
		}
    
		$string_exp = "/^[A-Za-z .'-]+$/";
  
		if(!preg_match($string_exp,$first_name)) {
		$error_message .= 'The First Name you entered does not appear to be valid.<br />';
		}
		
		if(!preg_match($string_exp,$last_name)) {
		$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
		}
		
		if(strlen($comments) < 2) {
		$error_message .= 'The Comments you entered do not appear to be valid.<br />';
		}
		
		if(strlen($error_message) > 0) {
		died($error_message);
		}
		
    	$email_message = "Form details below.\n\n";
     
		function clean_string($string) {
		  $bad = array("content-type","bcc:","to:","cc:","href");
		  return str_replace($bad,"",$string);
		}
     
		$email_message .= "First Name: ".clean_string($first_name)."\n";
		$email_message .= "Last Name: ".clean_string($last_name)."\n";
		$email_message .= "Email: ".clean_string($email_from)."\n";
		$email_message .= "Telephone: ".clean_string($telephone)."\n";
		$email_message .= "Comments: ".clean_string($comments)."\n";
     
     
		// create email headers
		$headers = 'From: '.$email_from."\r\n".
		'Reply-To: '.$email_from."\r\n" .
		'X-Mailer: PHP/' . phpversion();
		@mail($email_to, $email_subject, $email_message, $headers);  
		
?>
 
<!-- place your own success html below -->
 
<p>Thank you for contacting us. We will be in touch with you very soon.</p>
 
<?php
	die();
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>..:: Contact ::..</title>
</head>

<body>

<form name="htmlform" method="post" action="">
<table width="650px" height="400px">
</tr>
<tr>
 <td valign="top">
  <label for="first_name">Your Name <span class="asterix">*</span></label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input  type="text" name="first_name" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="50" size="35">
 </div>
 </td>
</tr>
 
<tr>
 <td valign="top"">
  <label for="last_name">Company Name</label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input type="text" name="last_name" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="50" size="35">
  </div>
 </td>
</tr>
<tr>
 <td valign="top">
  <label for="email">Email Address <span class="asterix">*</span></label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input type="text" name="email" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="80" size="35">
 </div>
 </td>
 
</tr>
<tr>
 <td valign="top">
  <label for="telephone">Telephone Number</label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input type="text" name="telephone" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="30" size="35">
  </div>
 </td>
</tr>
<tr>
 <td valign="top">
  <label for="comments">Message <span class="asterix">*</span></label>
 </td>
 <td valign="top">
 <div class="text_field_ta">
  <textarea name="comments" maxlength="1000" style=" border:none; width:460px; margin-top:3px; margin-left:3px;" cols="61" rows="12"></textarea>
 </div>
 </td>
 
</tr>
<tr>
<td></td>
 <td align="left" valign="middle">
 <input name="Submit" type="submit" class="send_c" value="Send Enquiry" />
 </td>
 </td>
</tr>
</table>
</form>

</body>
</html>

Open in new window

Author

Commented:
Thanks expert.

I have tested the code and it works fine.

The only problem now is that the error messages are displayed but the rest of the page content disappears.

I want the page content and everything to to be there and the error message displayed under the relevant form field.

Can you help with this please?
The reason for that is you have the errors being echoed during the validation.  If you want them to display along with the rest of the content, then instead of using echo of the error lines, assign the text to a concatenated variable and then echo it in the form page.

So instead of using die() in your died function, have it return the value of the error message so that you can output it in your form.

function died($error) {
	// your error code can go here
	$err = "We are very sorry, but there were error(s) found with the form you submitted. ";
	$err .= "These errors appear below.<br /><br />";
	$err .= $error."<br /><br />";
	$err .= "Please go back and fix these errors.<br /><br />";
	return $err;
}

Open in new window


Add an else condition after your $error_message check
if(strlen($error_message) > 0) {
	$errmsg = died($error_message);
}
else {
      # process rest of form then die on confirmation paragraph
}

Open in new window


Last part, output your $err message before the form.
<p>
<?php echo $errmsg; ?>
</p>
<form name="htmlform" method="post" action="">

Open in new window

Author

Commented:
I'm getting an error message Undefined variable: errmsg line ...

Author

Commented:
Everything else seem fine except for this error............
Try this:

<?php	
	if(isset($_POST['Submit'])) {
     
		// CHANGE THE TWO LINES BELOW
		$email_to = "tom@hotmail.com";
		$email_subject = "Website Inquiry Request";
     
		function died($error) {
			// your error code can go here
			$err = "We are very sorry, but there were error(s) found with the form you submitted. ";
			$err .= "These errors appear below.<br /><br />";
			$err .= $error."<br /><br />";
			$err .= "Please go back and fix these errors.<br /><br />";
			return $err;
		}
     
		// validation expected data exists
		if(!isset($_POST['first_name']) ||
			!isset($_POST['last_name']) ||
			!isset($_POST['email']) ||
			!isset($_POST['telephone']) ||
			!isset($_POST['comments'])) {
			died('We are sorry, but there appears to be a problem with the form you submitted.');      
		}
     
		$first_name = $_POST['first_name']; // required
		$last_name = $_POST['last_name']; // required
		$email_from = $_POST['email']; // required
		$telephone = $_POST['telephone']; // not required
		$comments = $_POST['comments']; // required
     
		$error_message = "";
		$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  
		if(!preg_match($email_exp,$email_from)) {
		$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
		}
    
		$string_exp = "/^[A-Za-z .'-]+$/";
  
		if(!preg_match($string_exp,$first_name)) {
		$error_message .= 'The First Name you entered does not appear to be valid.<br />';
		}
		
		if(!preg_match($string_exp,$last_name)) {
		$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
		}
		
		if(strlen($comments) < 2) {
		$error_message .= 'The Comments you entered do not appear to be valid.<br />';
		}
		
		if(strlen($error_message) > 0) {
			$errmsg = died($error_message);
		}
		
		else {
		
			$email_message = "Form details below.\n\n";
		 
			function clean_string($string) {
			  $bad = array("content-type","bcc:","to:","cc:","href");
			  return str_replace($bad,"",$string);
			}
		 
			$email_message .= "First Name: ".clean_string($first_name)."\n";
			$email_message .= "Last Name: ".clean_string($last_name)."\n";
			$email_message .= "Email: ".clean_string($email_from)."\n";
			$email_message .= "Telephone: ".clean_string($telephone)."\n";
			$email_message .= "Comments: ".clean_string($comments)."\n";
		 
		 
			// create email headers
			$headers = 'From: '.$email_from."\r\n".
			'Reply-To: '.$email_from."\r\n" .
			'X-Mailer: PHP/' . phpversion();
			@mail($email_to, $email_subject, $email_message, $headers);  
		
?>
 
<!-- place your own success html below -->
 
<p>Thank you for contacting us. We will be in touch with you very soon.</p>
 
<?php
	die();
}
	}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>..:: Contact ::..</title>
</head>

<body>
<p>
<?php echo $errmsg; ?>
</p>
<form name="htmlform" method="post" action="">
<table width="650px" height="400px">
</tr>
<tr>
 <td valign="top">
  <label for="first_name">Your Name <span class="asterix">*</span></label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input  type="text" name="first_name" value="<?php print $_POST["first_name"]; ?>" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="50" size="35">
 </div>
 </td>
</tr>
 
<tr>
 <td valign="top">
  <label for="last_name">Company Name</label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input type="text" name="last_name" value="<?php print $_POST["last_name"]; ?>" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="50" size="35">
  </div>
 </td>
</tr>
<tr>
 <td valign="top">
  <label for="email">Email Address <span class="asterix">*</span></label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input type="text" name="email" value="<?php print $_POST["email"]; ?>" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="80" size="35">
 </div>
 </td>
 
</tr>
<tr>
 <td valign="top">
  <label for="telephone">Telephone Number</label>
 </td>
 <td valign="top">
 <div class="text_field">
  <input type="text" name="telephone" value="<?php print $_POST["telephone"]; ?>" style="border:none; width:240px; margin-left:3px; height:17px; margin-top:3px;" maxlength="30" size="35">
  </div>
 </td>
</tr>
<tr>
 <td valign="top">
  <label for="comments">Message <span class="asterix">*</span></label>
 </td>
 <td valign="top">
 <div class="text_field_ta">
  <textarea name="comments" maxlength="1000" style=" border:none; width:460px; margin-top:3px; margin-left:3px;" cols="61" rows="12"><?php print $_POST["comments"]; ?></textarea>
 </div>
 </td>
 
</tr>
<tr>
<td></td>
 <td align="left" valign="middle">
 <input name="Submit" type="submit" class="send_c" value="Send Enquiry" />
 </td>
 </td>
</tr>
</table>
</form>

</body>
</html>

Open in new window

Author

Commented:
Hi Expert,

I tried the code and again the same error...

Please see attached screen shot.
php-error.png

Author

Commented:
Any ideas what could be the problem?
Did you use the exact code I provided or did you modify it in any way?  Can you repost the exact code you are using for contact2.php?