Email validation using PHP

I have a form for which i am trying to validate the email address. If the email address is incorrect i want a value of “Please type a valid email address.” to be returned into the “email” input box on the form. What am i doing wrong? No validation is taking place. I receive the form information at my email and once submitted the user is sent to the “Thank you” page, but no validation. I can put anything in the “email” input and the form will submit.

<form action="../php/contact.php" method="post">
  <p>First Name:</p>
   <input class="box_style" type="text" name="first_name" required maxlength="20" />

  <p>Last Name:</p>
   <input class="box_style" type="text" name="last_name" required maxlength="25" />

   <input class="box_style" type="text" name="email" required maxlength="50" />

   <p>Contact Number (optional):</p>
   <input class="box_style" type="text" name="contact_number" maxlength="12" />

  <p>How did you find us?</p>
  <select class="box_style" name="how" required>
    <option value="choose">Select...</option>
    <option value="referal">Referal</option>
    <option value="website">Website</option>
    <option value="search">Search Engine</option>
    <option value="card">Business Card</option>

  <textarea class="box_style" name="inquiries" cols="30" rows="10"></textarea>

  <input class="box_style" type="submit" name="submit" value="Submit"/>   

and this is the php


function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;

// define variables and set to empty values
$fName = $lName = $email = $cNum = $how =  $enquiries = "";

$fName = test_input($_POST["first_name"]);
$lName = test_input($_POST["last_name"]);
$cNum = test_input($_POST["contact_number"]);
$how = test_input($_POST["how"]);
$enquiries = test_input($_POST["enquiries"]);

$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    print  "<p>Please type a valid email address.</p>";

header("Location: www.mysite/");

$email_from = '';
$email_subject = "New Inquiry";
$email_body = "You have received a new message from" ." ". "$fName" ." ".    "$lName" ."n".
"Referal Type:" ." ". "$how" ."n".
"Contact Number:" ." ". "$cNum" ."n";

$to = "";
$headers = "From: $email_from rn";
$headers .= "Reply-To: $email rn";


Thank You

Source: stackoverflow-php

Leave a Reply

Your email address will not be published. Required fields are marked *