1

My mail form is still sending emails even if the email address is not valid. For example, if I fill in the email as "bob", and hit submit, my javascript validator gives a warning message, but the email still goes through. It ends up in my spam box as bob@mydomain.com

How can I validate the email address, and prevent submit if it does not validate?

I am new to php.

HTML:

 <div id="emailform">
                <h2>Confirm your purchase information</h2>
                <hr>
                <form method="post" name="contactform" action="mail_form.php" id="submit">
                <p>
                <label for='name'>Your Name:</label> <br>
                <input type="text" name="name">
                </p>
                <p>
                <label for='email'>Email Address:</label> <br>
                <input type="text" name="email">
                </p>
                <p>
                <label for='purchasecode'>Purchase Code:</label> <br>
                <input type="text" name="purchasecode">
                </p>
                <p>
                <label for='vendor'>Vendor Name:</label> <br>
                <select name="vendor">
                  <option value="" selected="selected"></option>
                  <option value="Amazon" >Amazon</option>
                  <option value="Barnes&Noble" >Barnes &amp; Noble</option>
                  <option value="Family Christian" >Family Christian</option>
                  <option value="Christianbook" >Christianbook.com</option>
                  <option value="LifeWay" >LifeWay</option>
                  <option value="BAM" >Books-A-Million</option>
                  <option value="Mardel" >Mardel</option>
                </select>
                </p>
                <button type="submit" id="submitbutton" name="submit" value="Submit" class="mainButton">SUBMIT</button><br>
                </form>

<!--            Code for validating the form
                Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
                for details -->
                <script type="text/javascript">
                var frmvalidator  = new Validator("contactform");
                frmvalidator.addValidation("name","req","Please provide your name");
                frmvalidator.addValidation("email","email","Please enter a valid email address");
                frmvalidator.addValidation("vendor","dontselect=000");
                frmvalidator.addValidation("purchasecode","maxlen=50");
                </script>
            </div>

PHP:

<?php
ini_set('display_errors',1);
 error_reporting(E_ALL);

if(!isset($_POST['submit']))
{
  //This page should not be accessed directly. Need to submit the form.
  echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$email = $_POST['email'];
$purchasecode = $_POST['purchasecode'];
$vendor = $_POST['vendor'];


//Validate first
if(empty($_POST['name'])  ||
   empty($_POST['email']) ||
   empty($_POST['purchasecode']) ||
   empty($_POST['vendor']))
{
    echo "All fields are required.";
exit;
}

if(IsInjected($email))
{
    echo "Bad email value!";
    exit;
}

$email_from = $email;
$email_subject = "GDFY Purchase Confirmation";
$email_body = "New purchase confirmation from $name.\n".
    "Here are the details:\n\n Name: $name \n\n Email: $email \n\n Purchase Code: $purchasecode \n\n Vendor: $vendor";

$to = "idc615@gmail.com";//<== update the email address

$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email_from \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: index.html');

// echo "success";


// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}

?>

Javascript:

  $('#submit').submit(function() { // catch the form's submit event
      $.ajax({ // create an AJAX call...
          data: $(this).serialize(), // get the form data
          type: $(this).attr('method'), // GET or POST
          url: $(this).attr('action'), // the file to call
          success: function(response) { // on success..
              $('#emailform').html("<h2 style='text-align:center;'>Thank you!</h2><hr><p style='text-align:center;'>Thank you for submitting your purchase information.<br>We will send your free gifts soon!</p>"); // update the DIV
          }
      });
      return false; // cancel original event to prevent form submitting
  });
eloist
  • 465
  • 3
  • 10
  • 22
  • 2
    Seriously, use a decent mailer class like PHPMailer or Swiftmailer -- it does all this kind of stuff for you, and does it right. – Spudley Sep 04 '13 at 14:21
  • `if( // condition email == false) {echo "Bad email value!"; } else { // HERE YOUR MAIL SCRIPT }` – Black Sheep Sep 04 '13 at 14:21
  • You could use `$email_check = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";` instead of what you have or add to it, then use `if(!preg_match($email_check,$email)){ die("Please enter a valid email address!"); }` – Funk Forty Niner Sep 04 '13 at 14:26
  • if( // condition email == false) {echo "Bad email value!"; } else { // HERE YOUR MAIL SCRIPT }This seems to stop the bad emails from sending, however, my javascript still refreshes that div with a success message. How can I prevent this? – eloist Sep 04 '13 at 14:28
  • @eloist You need to check for valid characters. As in my example above (edited) comment. It works, but there's room for improvement. – Funk Forty Niner Sep 04 '13 at 14:32
  • Having trouble with this. Sorry guys, I'm new to php. – eloist Sep 04 '13 at 14:37
  • @eloist No problemo. Have a look at my answer below, it's what I use. Just don't use your `name="contactform"`. It makes use of the `FILTER_VALIDATE_EMAIL` option. – Funk Forty Niner Sep 04 '13 at 15:04

6 Answers6

2

You can use filter_var :

if( filter_var('bob@example.com', FILTER_VALIDATE_EMAIL) )
{
    Do_stuff();
}
Scalpweb
  • 1,971
  • 1
  • 12
  • 14
0

I'd recommend filtering on both front and back end. Front end to prevent unnecessary hits to the server and to provide more effective and prompt feedback, and back end to catch anything that the Front-end lets through (since it can be bypassed)

My script of choice for the front end is jQuery Ketchup

On the back-end, filter_var works fine, as does regex if you're working with an older version of PHP.

Community
  • 1
  • 1
bpeterson76
  • 12,918
  • 5
  • 49
  • 82
0

This is what I use and it works well, using Ajax and jQuery. You're welcome to use it and modify to suit.

Both HTML form and PHP handler are included.

HTML form

<!DOCTYPE html>

<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){

    $('#submit').click(function(){
        $('#success').hide(1);
        $.post("ajax_handler.php", $("#contact").serialize(),  function(response) {
            $('#success').html(response);
            $('#success').show(1000);
        });
        return false;

    });

});
</script>

<style>

html {
/*    height: 100%; */

height:auto;
}
body {
    background:#000;
/*  background: url(bg.png);
    background-repeat:repeat;*/
    margin: 0px;
    padding: 0px;
    height: 100%;
    color: #fff;
    font-family: Proxima, sans-serif;;
}


#empty {
    display:block;
    clear:both;
    height:150px;
    width:auto;
    background:none;
    border:none;
}


#contact ul{
    margin-left:10px;
    list-style:none;
}


#contact ul li{
    margin-left:0px;
    list-style:none;
}

</style>

</head>

<body>

<form id="contact" action="" method="post">
<ul>
    <li>
        <label for="name">Name:</label><br>
        <input id="name" type="text" name="name"  width="250" size="35" required/>
    </li>
    <li>
        <label for="email">Email:</label><br>
        <input id="email" type="text" name="email" width="250" size="35" required/>
    </li>
<br><br>
    <li>
        <label for="message">Message:</label><br>
        <textarea id="message" name="message" rows="6" cols="40" required></textarea>
    </li>
    <li><input type="button" value=" SEND " id="submit" /><input type="reset" value="Reset" name="reset">
<div id="success" style="color: yellow;"></div></li>
</ul>


</form>
</body>

</html>

Handler (ajax_handler.php)

<?php

if((empty($_POST['name'])) || (empty($_POST['email'])) || (empty($_POST['message']))){

die("<b>ERROR!</b> All fields must be filled.");

}

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

$name = strtolower($name);
$name = ucwords($name);

$to = 'email@example.com';
$subject = 'Website message from: '.$name;
$message = 'FROM: '.$name." \nEmail: ".$email."\nMessage: \n".$message;
$headers = 'From: your_email@example.com' . "\r\n";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) { 
mail($to, $subject, $message, $headers); 
echo "Thank you! Your email was sent $name.";
echo "<br>";
echo "This is the email you entered: <b>$email</b>";
}else{
// echo var_dump($_POST);
echo "<b>ERROR!</b> Invalid E-mail. Please provide a valid email addres. Example: myEmail@example.com";
echo "<br>";
echo "The email <b>$email</b> you entered, is not valid.";
}

?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

$email = test_input($_POST["email"]); if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "Invalid email format"; }

you can use this Ihave tried just onw it's working

gihansalith
  • 1,770
  • 5
  • 17
  • 21
0
Javascript validation
<script type="text/javascript">
var a = document.contact_form.txt_phoneno.value;
        if (a!="")
        {
        if(isNaN(a))
        {
        alert("Enter the valid Mobile Number(Like : 9566137117)");
        document.contact_form.txt_phoneno.focus();
        return false;
        }
        if((a.length < 10) || (a.length > 15))
        {
        alert(" Your Mobile Number must be 10 to 15 Digits");
        document.contact_form.txt_phoneno.select();
        return false;
        }
        }
</script>
dev4092
  • 2,820
  • 1
  • 16
  • 15
0

try this preg match

$email = test_input($_POST["email"]);
if (!preg_match("/^[\w-]+[@]+[a-z]+\.+[a-z]*$/", $email)) {
  return false; 
  //exit;
}
antelove
  • 3,216
  • 26
  • 20