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>
<html>
<head>
<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; }
      </style>
</head>
<body>
<form method = "post" >
<h1>Enter an email address</h1>
<p><label>Email:
<input email = "email" type = "text" size = "25" maxlength = "45">
</lable></p>

<p><input type = "submit" value = "Submit"></p>
<?php 
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 
?> 

</body>
</html>

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?

Would it not just be easier to use:

<?php
$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:

if(!validate_email($_POST['email']))
{
   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 :)

Yes this did help thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.