How To Validate My Form

Can someone take a look at this code below and tell me how I can make sure that someone has simply entered an email address inside the form field? I do not need it to verify/test the DNS or SMTP.

<!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=UTF-8" />
<title>About</title>
<link rel="stylesheet" href="../c/style.css" type="text/css" media="screen"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<div id="outer">
	<?php include("../test/includes/header.html") ?>
	<div id="wrapper">
		<div id="main">
          <div id="left">
          	<h2>About</h2>
          	<p>Here is some body copy. </p>
            <p>&nbsp;</p>
          </div>
          <!--end left-->
          <div id="right">
          	<div class="box1">
            	<h2>Email Newsletter</h2>
  <?php
/*	==============================================================================
	FUNCTION TO VALIDATE EMAIL ADDRESS
	============================================================================== */
	function isEmail($email) {
		// CREATE THE SYNTACTICAL VALIDATION REGULAR EXPRESSION
		$regexp = "^([_a-z0-9-]+)(\\.[_a-z0-9-]+)*@([a-z0-9-]+)(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$";

		// PRESUME THAT THE EMAIL IS INVALID
		$valid = 0;

		// VALIDATE THE SYNTAX
		if (eregi($regexp, $email)) {
			$valid = 1;
		}
		return $valid;
	}

/*	==============================================================================
	DEFINES DEFAULT FORM FIELD VALUES
	============================================================================== */
	if(!isset($_POST['contact_email'])) { $_POST['contact_email'] = "email address"; }
	if(!isset($_POST['contact_message'])) { $_POST['yourMessage'] = ""; }

	//	EMAIL NOT SENT BY DEFAULT
	$emailSent = 0;

/*	==============================================================================
	IF FORM HAS BEEN SUBMITTED, CHECK FOR ERRORS, IF NO ERRORS, SEND EMAIL
	============================================================================== */
	if(!isset($formError)) { $formError = array(); }
	if (isset($_POST['submit'])) {

		//	SEND EMAIL IF NO ERRORS
		$formError = array(); 
		if($_POST['contact_email']=="")
		{
			$formError[]="Please Enter An Email Address\
";
		}
		if(count($formError) == 0) {

			//	IF NO MESSAGE TYPED, SET TO "NO MESSAGE ENTERED"
			if (strlen(trim($_POST['contact_message'])) == 0) {
				$_POST['yourMessage'] = "No Message Entered by Visitor";
			}

			//	CREATE EMAIL BODY
			$theBody = $theBody . "Email: " . $_POST['contact_email'] . "\
";
			$theBody = $theBody . "Sent: " . date('m-d-Y', time()) . " " . date('g:i A', time()) . "\
\
";

			//	DEFINE EMAIL TO SEND TO
			$emailTo = "myemail@domain.com";
			$emailSubject = "Newsletter Sign-Up";
			$headers = 'From: no-reply@domain.com' . "\\r\
" .
					   'Bcc: name@domain.com' . "\\r\
"  .
				       'Reply-To: no-reply@domain.com' . "\\r\
" ;

			//	SEND EMAIL
			mail($emailTo, $emailSubject, $theBody, $headers);

			$emailSent = 1;
		}
	}
?>
<?php if($emailSent) { ?>
<!-- SUBMIT CONFIRMATION -->
<p><strong>Thank you!</strong> Your email has been sent.</p>             
<?php } else {
if(count($formError) == 0) { ?>
<?php } else { echo "<ul>"; foreach($formError as $e) { echo "<li class=\\"error\\">$e</li>"; } echo "</ul><br />"; }?>
<p>Sign up to receive breaking news as well as receive other site updates!</p>
<form id="signup" name="signup" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<table border="0" cellpadding="3" cellspacing="0">
	<tr>
		<td valign="baseline">
		<input id="email" name="contact_email" type="text" value="<?php echo $_POST['contact_email'] ?>" size="26" tabindex="1" />
		<input name="submit" type="image" id="submit" value="go" src="../i/btn_go.gif" alt="Go" /></td>
	</tr>
</table>
</form>
<?php } ?><!--end signup-->
          	</div><!--end box1-->
          </div><!--end right-->
	  </div><!--end main-->
    </div><!--end wrapper-->
</div><!--end outer-->
<script type="text/javascript">var form=document.getElementById('signup');form.elements.contact_email.onclick=clearDefault;function clearDefault(){if(this.value===this.defaultValue){this.value='';}}</script>
<script type="text/javascript">
<!--
	$(document).ready(function(){
		$("#signup").validate({
			wrapper: "li",									
			rules: {contact_email: {required:true},},
			highlight: function(element, errorClass) {$(element).css('border','1px solid red');},
			unhighlight: function(element, errorClass) {$(element).removeAttr('style');}
		});		
	}); 	
//-->
</script>
</body>
</html>

This will do that for you. :slight_smile:


<?php
function isValidEmail($email){
  return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
}

var_dump(
  isValidEmail(filter_input(INPUT_POST, 'email'))
);
?>

I have added that code and it simply added the text “bool(false)” to the text within that DIV.

I am ultimately wanting someone to not be able to click on the submit button without entering an email address. Currently you can hit the “Go/Submit” button and an email is being sent without any message.

I need the email to be required.
Thanks for looking into this!

You cannot copy the sample code verbatim, it merely demonstrates how to check for a valid email address.

For example…


<?php
function isValidEmail($email){
  return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
}

$isValidEmail = isValidEmail(filter_var(INPUT_POST, 'email'));

if($isValidEmail){
  #email is fine
}else{
  #email isn't, fine that is.
}
?>

I am not proficient at writing PHP and that is where I would need help. I am having problems integrating your code into my existing code that someone else has written. I am still learning and I cannot quite understand where the if/else statement would go since there is already one in my code. Would I simply add $isValidEmail into my existing if/else statement?

OK. :wink:

Replace…


    function isEmail($email) {

        // CREATE THE SYNTACTICAL VALIDATION REGULAR EXPRESSION

        $regexp = "^([_a-z0-9-]+)(\\.[_a-z0-9-]+)*@([a-z0-9-]+)(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$";



        // PRESUME THAT THE EMAIL IS INVALID

        $valid = 0;



        // VALIDATE THE SYNTAX

        if (eregi($regexp, $email)) {

            $valid = 1;

        }

        return $valid;

    }

With…


function isValidEmail($email){
  return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
}

Then, replace…


        if($_POST['contact_email']=="")

        {

            $formError[]="Please Enter An Email Address\
";

        }

With…


        if(false === isValidEmail($_POST['contact_email']))
        {

            $formError[]="Please Enter A Valid Email Address\
";

        }

That should do it, I think. :smiley:

That did the trick. You are the man! Thank you so much.
Todd

Glad to hear it, you’re most welcome.