I have an assignment that I have been working on for the past few days that is making me go crazy. The instructions are as follows:

Write a PHP script that tests whether an e-mail address is input correctly. Verify that the input begins with series of characters, followed by the @ character, another series of characters, a perod (.) and a final series of characters. Test your program, using both valid and invalid e-mail address.

Here is the code I have:

<!DOCTYPE html>
<meta charset= "utf-8">
 <title>Email Validation</title>
      <style type = "text/css">
         p          { margin: 0px; }
         .error     { color: red }
         p.head     { fong-weight: bold; margin-top: 10px; }
<form method = "post" >
<h1>Enter an email address</h1>
<input email = "email" type = "text" size = "25" maxlength = "45">

<p><input type = "submit" value = "Submit"></p>
function validate_email($email) { 

//check for all the non-printable codes in the standard ASCII set, 
//including null bytes and newlines, and exit immediately if any are found. 
if (preg_match("/[\\000-\\037]/",$email)) { 
return false; 
$pattern = "/^\[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD"; 
if(!preg_match($pattern, $email)){ 
return false; 
// Validate the domain exists with a DNS check 
// if the checks cannot be made (soft fail over to true) 
list($user,$domain) = explode('@',$email); 
if( function_exists('checkdnsrr') ) { 
if( !checkdnsrr($domain,"MX") ) { // Linux: PHP 4.3.0 and higher & Windows: PHP 5.3.0 and higher 
return false; 
else if( function_exists("getmxrr") ) { 
if ( !getmxrr($domain, $mxhosts) ) { 
return false; 
return true; 
} // end function validate_email 


This is working to a certain point but what I really want is to hit submit and have it tell me if it is a valid email address or an invalid email address but I do not know where to place this or how to get it to print the two statements when checking the email addresses. Can anyone help me?

Edited by pritaeas: Moved.

3 Years
Discussion Span
Last Post by ncis_sg1

Would it not just be easier to use:

$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_a) email address is considered valid.";

PHP already has this built-in!!

But, what you have used is a function, to call this function you would use:

   die("you have not used a correct email address");

// or 

$email = $_POST['email'];
if(!validate_email($email)) {
   die("you have not used a correct email address");

Hope this helps :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.