How to validate email in HTML form with PHP

1 Answer

0 votes
<!DOCTYPE HTML>
<html>
<head>
<style>
.error_message {color: #FF0000;}
</style>
</head>
<body>

<?php
$err_msg = "";
$email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") 
{
    if (empty($_POST["email"])) 
    {
        $err_msg = "Email is required";
    } 
    else 
    {
     $email = clean_input($_POST["email"]);
     // check if $email is a valid e-mail address
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) 
     {
         $err_msg = "Invalid email";
     }
   }
}
function clean_input($data) 
{
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   
   return $data;
}
?>

<h3>Form Validation With PHP</h3>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
   Email: <input type="text" name="email">
   <span class="error_message">* <?php echo $err_msg;?></span>
   <br /><br />
   <input type="submit" name="submit" value="Submit">
</form>

<?php
echo "email = " . $email;
?>

</body>
</html>

 



answered Nov 23, 2015 by avibootz

Related questions

2 answers 306 views
306 views asked Nov 19, 2018 by avibootz
1 answer 264 views
1 answer 258 views
1 answer 210 views
...