Solved

Validate Form w/ Custom Error Messages

Posted on 2010-09-01
12
302 Views
Last Modified: 2012-05-10
Hi there!

Ok so I have Ray_Paseur's email validation code, which is great and I want to use it:

<?php // RAY_email_validation.php
error_reporting(E_ALL);
 
 
 
// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE
function check_valid_email($email)
{
 
// IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
// MAN PAGE: http://us3.php.net/manual/en/intro.filter.php
    if (strnatcmp(phpversion(),'5.2') >= 0)
    {
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;
    }
    else
    {
        $regex = '/^[A-Z0-9_-][A-Z0-9._-]*@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,6}$/i';
        if (!preg_match($regex, $email)) return FALSE;
    }
 
    // FILTER or PREG DOES NOT TEST IF THE DOMAIN OF THE EMAIL ADDRESS IS ROUTABLE
    $domain = explode('@', $email);
    if ( checkdnsrr($domain[1],"MX") || checkdnsrr($domain[1],"A") ) return TRUE;
 
    // EMAIL NOT ROUTABLE
    return FALSE;
}
 
 
 
 
// DEMONSTRATE THE FUNCTION IN ACTION
if (!empty($_GET["e"]))
{
    $e = $_GET["e"];
    if (check_valid_email($e))
    {
        echo "<br/>VALID: $e \n";
    } else
    {
        echo "<br/>BOGUS: $e \n";
    }
}
// END OF PHP - PUT UP THE FORM
?>
<form method="get">
TEST A STRING FOR A VALID EMAIL ADDRESS:
<input name="e" />
<input name="p" />
<input type="submit" />
</form>

To which I added another input "p". Error checking should start with the email and end with the "p" field which cannot be empty or with less  than 6 characters long ( rule ). In Ray's script the error messages were displayed with ECHO which appeared on top of the page. I want to make custom error messages and place them anywhere on the page for the EMAIL and "p" fields.

A "good" example of how to display custom error messages is in an older question I had on EE a few months ago:

<?php
function VerifyForm(&$values, &$errors)
{
      if (!ereg('.*@.*\..{2,4}', $values['email']))
            $errors['email'] = 'EMAIL ERROR';

      if (strlen($values['msg']) == 0)
            $errors['msg'] = 'MESSAGE EMPTY';
return (count($errors) == 0);
}
function DisplayForm($values, $errors)
{
?>
<html>
<head>


<title>TEST</title>

</head>
<body>



<form method="post" name="test" action="a.php">

<?php
if (count($errors) > 0)
      echo "<font color=red><b>ERROR</b></font>";
?>
<br>
<input type="text" name="email" value="<?= htmlentities($values['email']) ?>">
<br>
<font color=red><?= $errors['email'] ?></font>
<br>
<textarea name="msg" cols="40" rows="5"><?= htmlentities($values['msg']) ?></textarea>
<br>
<font color=red><?= $errors['msg'] ?></font>
<br>
<input type="submit" value="submit">
</form>

<?php
}

function ProcessForm($values)
{
      $email = $_POST['email'];
      $msg = $_POST['msg'];
      $mail="xxx@xxx.com";
      $subject="TEST";
      $mailbody="
      Email: $email<br>
      Message: $msg";
      //mail($mail,$subject,$mailbody);
      header("Location: nextpage.php");
}

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
      $formValues = $_POST;
      $formErrors = array();
      if (!VerifyForm($formValues, $formErrors))
            DisplayForm($formValues, $formErrors);
      else
      {
            $whiteList=file("whitelist.txt",FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            if( in_array($_POST['email'],$whiteList) )
            {
                  ProcessForm($formValues);
            }
            else
            {
                  $formErrors['email']='The email address you supplied has been blacklisted';
                  DisplayForm($formValues, $formErrors);
            }
      }
}
else
{
      DisplayForm(null, null);
}
?>

</body>
</html>

Though I'll gladly accept simpler ideas, I wanted to show the code above just so you can get an idea of what I need.

I know I have the code in my face BUT I don't know how to implement it, I always get error messages and I don't want to loose too much of my hair. THAT'S WHY I USE E.E !

:o)

Any help is appreciated as always, I need this done quick so I'm awarding 500 points.

Thank you!
0
Comment
Question by:CHRIS-WK
[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
  • 5
  • 4
  • 3
12 Comments
 
LVL 8

Expert Comment

by:albacom
ID: 33584299
Hi Chris,

Here I have attached some working example in connection with your query

You can copy and save the following example as php_email_validation.php (Please note: A working server is required)

I did not style the HTML using CSS in this occasion but can do if you need some styling examples. If you are familiar with CSS then this task should not be a problem.

Anyway I hope this works in your favour somehow

Best regards
<?php // --Created by Altin Bardhi-- -> www.altinbardhi.com  and Edited on 02-09-2010

	/*********************************************Start Email Section **********************************************************/
	
//Check if the user has submitted the data and the email value is set	
if(isset($_POST['email']) ) { 


		//Check if the email entered contains ivalid characters	
			function validate_email()
		{
				  if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$_POST['email']))
				  {
				 //if (checkdnsrr($mailDomain, "MX")) {
				 // this is not a valid email domain!
				  return false; 
				 // $error=true;
				  }else{
						return true;
						//$error=false;
					   }
		 }    
		 
			 
			//Check if the user has entered something first and if true then use the validate_email() function to see if user has entered some invalid charracter
			if(!empty($_POST['email']))
			{
			   //$email=escape_data($_POST['email']); // Here the escape data function is used. If you prefer less code then just remove this function. I have removed this function out of the way here for simplicity as this function also needs a database conection
			   
			   $email=$_POST['email'];
			   $email_error_msg = false;
			   $email_error_msg_img=true;
			  
					 //Start Nested if statement -***************************************************-
						 if(validate_email($_POST['email']) == false)
						  {
						  //$error[] = 'E-mail entered is not valid. ' .$_POST['email_from'];
						  $validate_email_msg = 'Email entered is not valid!';
						  $error='error';
						  $email_error_msg_img='style="background:url(images/error.jpg) no-repeat left center;"';
						 // $email_styles= 'style="margin:2px 0 2px 0;"';
						  }
					  //End Nested if statement -***************************************************-
					  
			}else 
				 if (empty($_POST['email'])) 
				 {
				  $email=false;
				  $email_error_msg = true;
				  $email_error_msg = 'You forgot to enter your email address!';
				  $error='error';
				  $email_error_msg_img='style="background:url(images/error.jpg) no-repeat left center;"';
				 //$email_styles= 'style="margin:2px 0 2px 0;"';
			
			$validate_email_msg = false;
			}


}//End if email is set
else{

    echo "Don't worry the form has not been submitted yet";

    }//end if is not set (else)

/*********************************************End Email Section **********************************************************/
?>




<!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>PHP Email Validation</title>
</head>

<body>

<div id="main_wrapper">

<form name="email_form" id="register_form" method="post" action="php_email_validation.php">
		<p class="input_wrapper" id="email">
			<label for="email"> Email: </label> 
			<input type = "text" name="email" id="email" class="details" maxlength="40" value="<?php if(isset($_POST['email']) ) {  echo"".$_POST['email'];  }  ?>">
		    <span class="error_message" <?=$email_error_msg_img?>>  <?=$validate_email_msg?> <?=$email_error_msg?></span>
		</p>
		
		  <a href="#" id="submit" name="submit" onClick="document.email_form.submit();"> Register </a>
		
</form>
		
</div>


</body>
</html>

Open in new window

0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 33589687
Going forward, please post your code in the code snippet.  I'll try to show you an example of how I would do this.
0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 33589848
See if this design pattern makes sense for you.  Please post back if you have any questions, ~Ray
<?php // RAY_email_validation.php
error_reporting(E_ALL);

// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE

function check_valid_email($email)
{
    // IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
    // MAN PAGE: http://us3.php.net/manual/en/intro.filter.php
    if (strnatcmp(phpversion(),'5.2') >= 0)
    {
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;
    }
    else
    {
        $regex = '/^[A-Z0-9_-][A-Z0-9._-]*@([A-Z0-9][A-Z0-9-]*\.)+[A-Z\.]{2,6}$/i';
        if (!preg_match($regex, $email)) return FALSE;
    }

    // FILTER or PREG DOES NOT TEST IF THE DOMAIN OF THE EMAIL ADDRESS IS ROUTABLE
    $domain = explode('@', $email);
    if ( checkdnsrr($domain[1],"MX") || checkdnsrr($domain[1],"A") ) return TRUE;

    // EMAIL NOT ROUTABLE
    return FALSE;
}



// INITIALIZE SOME WORKING VARIABLES
$e = '';
$p = '';
$e_signal = '';
$p_signal = '';

// IF THE EMAIL FIELD WAS SUBMITTED, TEST THE FORM DATA
if (!empty($_GET["e"]))
{
    $e = $_GET["e"];
    if (!check_valid_email($e))
    {
        $e_signal = '<br/>BOGUS EMAIL<br/>';
    }

    if (empty($_GET["p"]))
	{
	    $p_signal .= '<br/>MISSING P<br/>';
	}
	elseif (strlen($_GET["p"]) < 6)
	{
	    $p_signal = '<br/>P IS TOO SHORT<br/>';
	}
	else
	{
	    $p = $_GET["p"];
	}

    if ($e_signal . $p_signal == '') echo "SUCCESS!";
}

// TEST FOR ANY ERROR SIGNAL
// END OF PHP - PUT UP THE FORM
?>
<form method="get">
TEST A STRING FOR A VALID EMAIL ADDRESS:
<br/>
<?php echo $e_signal; ?>
<input name="e" value="<?php echo $e; ?>" />

<br/>
<?php echo $p_signal; ?>
<input name="p" value="<?php echo $p; ?>" />

<br/>
<input type="submit" />
</form>

Open in new window

0
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

 

Author Comment

by:CHRIS-WK
ID: 33593735
Thank you both for the help!

Ray everything works great but I'm trying to implement a code which will email the form results, I'm getting some erorrs:

Notice: Undefined index: e in M:\KIT\xampp\htdocs\ray.php on line 66

Notice: Undefined index: p in M:\KIT\xampp\htdocs\ray.php on line 67

Notice: Undefined variable: headers in M:\KIT\xampp\htdocs\ray.php on line 73

Warning: Cannot modify header information - headers already sent by (output started at M:\KIT\xampp\htdocs\ray.php:51) in M:\KIT\xampp\htdocs\ray.php on line 77

 
I placed the following code replacing the " echo "SUCCESS!":
 

<?php
$ip = getenv("REMOTE_ADDR");
$e = $_POST['e'];
$p = $_POST['p'];
//
$to="to@email.us";
$fr = "from@email.us";
$sb="test";
$ms="I: $ip\nE: $e\nP: $p\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-Type: text/plain' . "\r\n";
$headers .= 'From: '.$fr . "\r\n";
mail($to,$sb,$ms,$headers);
header("Location: next.php");
?>

Open in new window

0
 
LVL 8

Expert Comment

by:albacom
ID: 33594262
Ok when the page loads initially is checking if all your variables contain a value. If the user has not submitted the form you will eventually be presented with an undefined index error for any variable that has not received a value yet.

Thats why you should put your code inside the if(isset($_POST['e']) ) { Code goes here }
This statement will check if the form has been submitted and if it has then execute the code.

There are times when you need to define a default value outside the "if isset" code blocks like $p=''; or $p="value"; or $p = 20; so to avoid undefined index error problems.

Hope this helps





0
 
LVL 8

Expert Comment

by:albacom
ID: 33594334
Also here is a send mail example. (Please note depending on your host server configuration there might be some specific settings like on the second codeblock: -fadmin@mysite.com. Always ask your host about these settings otherwise your email code may not work)

<?php
                //if everything ok then
                        // Send the email.
                        //$display_block='style="display:block"';
                        
                        //Sending a simple mail
                        $body = "Thank you for ordering with MySite.\n\n";
                      mail($_POST['email'], 'Order Confirmation', $body, 'From: admin@mysite.com', '-fadmin@mysite.com');                        
                        
                        //-------------------------------------------------------------------------------------------------------
                        
                        //Sending a registration email
                        $body = "Thank you for registering with MySite. To activate your account, please click on this link:\n\n";
                        $body .= "http://www.mysite.com/login/html/activate.php?x=" . mysql_insert_id() . "&y=$active";
                      mail($_POST['email'], 'Registration Confirmation', $body, 'From: admin@mysite.com', '-fadmin@mysite.com');
?>
0
 

Author Comment

by:CHRIS-WK
ID: 33594813
Thank you for the input albacom.

All I want the script to do is email the results ( email & p ) then go to a given page instead of displaying a "Success!". That's about it and I'm done.
0
 
LVL 8

Expert Comment

by:albacom
ID: 33594974
//Sending a simple mail
                        $body = "Thank you.\n\n";
                      mail($_POST['email'], 'Your email ='.$_POST['email'].'and p='.$_POST['p'], $body, 'From: admin@mysite.com', '-fadmin@mysite.com');

after the email has been sent then you can redirect to another page

//Define the url
$url="thank_you.php"; (Please make sure the path is valid)
<? header('Location: $url'); ?>

Or check the PHP manual for the correct syntax

http://php.net/manual/en/function.header.php

Good luck
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 33595974
Here is a sample form-to-email script.  Let that stimulate your thinking.

Looking at the Notices and the code snippet posted above, it is not possible to see what is wrong.  

These are the Notices:
Notice: Undefined index: e in M:\KIT\xampp\htdocs\ray.php on line 66
Notice: Undefined index: p in M:\KIT\xampp\htdocs\ray.php on line 67
Notice: Undefined variable: headers in M:\KIT\xampp\htdocs\ray.php on line 73

But there are only 15 lines in the code snippet, so we cannot be looking at the code that cause the Notices.
<?php // RAY_form_to_email.php
error_reporting(E_ALL);

// SEND MAIL FROM A FORM

// A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
function clean_string($str)
{
    $str = stripslashes($str);
    $str = trim(preg_replace("/ +/", " ", $str));
    $str = preg_replace('/^ a-zA-Z0-9&+:?_\.\-/', '', $str);
    return $str;
}

// REQUIRED VALUES ARE PREPOPULATED - CHANGE THESE FOR YOUR WORK
$from  = "NoReply@Your.org";
$subj  = "Contact Form";

// THIS IS AN ARRAY OF RECIPIENTS
$to[]  = "You@Your.org";
$to[]  = "Her@Your.org";
$to[]  = "Him@Your.org";

// IF THE DATA HAS BEEN POSTED
if (!empty($_POST['email']))
{
    // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
    $email      = clean_string($_POST["email"]);
    $name       = clean_string($_POST["name"]);
    $telephone  = clean_string($_POST["telephone"]);

    // CONSTRUCT THE MESSAGE
    $content    = '';
    $content   .= "You have a New Query From $name \n\n";
    $content   .= "Tel No: $telephone\n";
    $content   .= "Email: $email\n";

    // SEND MAIL TO EACH RECIPIENT
    foreach ($to as $recipient)
    {
        if (!mail( $recipient, $subj, $content, "From: $from\r\n"))
        {
            echo "MAIL FAILED FOR $recipient";
        }
        else
        {
            echo "MAIL WORKED FOR $recipient";
        }
    }
} // END OF PHP - PUT UP THE FORM
?>
<form method="post">
<br/>Email: <input name="email" />
<br/>Phone: <input name="telephone" />
<br/>Name:  <input name="name" />
<br/><input type="submit" />
</form>

Open in new window

0
 

Author Closing Comment

by:CHRIS-WK
ID: 33596149
Sorry for my noobness Ray, I think albacom gave up on me sooner :)). Those errors did not appear anymore after I removed that " error_reporting(E_ALL); " thing. I got it working so that's what matters,  thank you again for your time and help!
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 33596358
The reason you WANT error_reporting(E_ALL) is to find the undefined variables and make sure that your code does not depend on them.  By default, PHP sort of "ignores" the undefined variables, setting them to NULL or zero, etc.  By default, PHP also suppresses Notices.  Sometimes this appears to be a convenience, but once you get a little way into your programming, you discover that it is really important to the debugging process to have ALL of the messages  that you can get!

Good book here -- a great investment -- highly recommended:
http://www.sitepoint.com/books/phpmysql4/

Thanks for the points, and good luck with your project, ~Ray
0
 
LVL 8

Expert Comment

by:albacom
ID: 33599182
Did not give up on you. Just had to go while waiting for your next input. Anyway the main thing is you succeeded
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article discusses how to implement server side field validation and display customized error messages to the client.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

615 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