This is related to a homework assignment. I have some code from my PHP textbook that doesn’t seem to work properly. The page asks for a name, email, subject and message, but it always echoes “”$fieldName" is not a valid e-mail address.
\n" from the else part of the validateEmail function. I think the issue is (and I don’t entirely understand this part) “/^[\w-]+(.[\w-]+)@" . "[\w-]+(.[\w-]+)” . “(.[[a-z]]{2,})$/i”. I get that it’s being compared to the string that was entered in the email field, but I don’t know what it’s specifically looking for. I hate asking for help, but if anyone could steer me in the right direction, I would be very grateful.
[php]
Contact Me <?php function validateInput($data, $fieldName) { global $errorCount; if (empty($data)) { echo "\"$fieldName\" is a required field.\n"; ++$errorCount; $retval = ""; } else { $retval = trim($data); $retval = stripslashes($retval); } return($retval); }
function validateEmail($data, $fieldName) { //this is the function I’m currently stuck on I believe
global $errorCount;
if (empty($data)) {
echo “”$fieldName" is a required field.
\n";
++$errorCount;
$retval = “”;
} else {
$retval = trim($data);
$retval = stripslashes($retval);
$pattern = “/^[\w-]+(.[\w-]+)@" . "[\w-]+(.[\w-]+)” . “(.[[a-z]]{2,})$/i”;
if (preg_match($pattern, $retval)==0) {
echo “”$fieldName" is not a valid e-mail address.
\n";
++$errorCount;
}
}
return($retval);
}
function displayForm($Sender, $Email, $Subject,
$Message) {
?>
Contact Me
Your Name:
Your E-mail:
Subject:
Message:
<?php echo $Message;
?>
<?php }
$ShowForm = TRUE;
$errorCount = 0;
$Sender = “”;
$Email = “”;
$Subject = “”;
$Message = “”;
if (isset($_POST[‘Submit’])) {
$Sender = validateInput($_POST[‘Sender’],“Your Name”);
$Email = validateEmail($_POST[‘Email’],“Your E-mail”);
$Subject = validateInput($_POST[‘Subject’],“Subject”);
$Message = validateInput($_POST[‘Message’],“Message”);
if ($errorCount==0)
$ShowForm = FALSE;
else
$ShowForm = TRUE;
}
if ($ShowForm == TRUE) {
if ($errorCount>0)
echo “
Please re-enter the form information below.
\n”;displayForm($Sender, $Email, $Subject, $Message);
}
else {
$SenderAddress = “$Sender <$Email>”;
$Headers = “From: $SenderAddress\nCC: $SenderAddress\n”;
$result = mail("[your email here]", $Subject, $Message, $Headers);
if ($result)
echo "
Your message has been sent. Thank you, " . $Sender . “.
\n”;else
echo "
There was an error sending your message, " . $Sender . “.
\n”;}
?> [/php]