Ad

Contactform Send Mail While Required Fields Are Not Filled

- 1 answer

I would like to setup my contact form like this that there will be no mail sent if the required fields are not filled in. If I click 'submit' there is still a mail being sent. Could someone help me out to the good direction to solve it? I only want that the mail will be sent if all required fields are filled in.

<?php


$nameErr = $emailErr = "";
$naam = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["naam"])) {
    $nameErr = "Wij willen graag weten hoe u heet!";
  } else {
    $naam = test_input($_POST["naam"]);
  }

  if (empty($_POST["email"])) {
    $emailErr = "Zonder een mailadres kunnen wij uw mail niet beantwoorden";
  } else {
    $email = test_input($_POST["email"]);
  }

}

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

if(isset($_POST['submit']))
{
    $naam = $_POST['naam'];
    $email = $_POST['email'];
    $onderwerp ="Contactformulier ingevuld door $naam";
    $bericht = $_POST['bericht'];
    $CS = "[email protected]";
    $afzender = "Googla BV";

    $headers = 'From: GoogleBV <[email protected]>' . "\r\n" .
    'Reply-To: ' . $email . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    mail($CS, $onderwerp, $bericht, $headers);

}


 ?>
Ad

Answer

You should do it this way:

<?php


$nameErr = $emailErr = "";
$naam    = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["naam"])) {
        $nameErr = "Wij willen graag weten hoe u heet!";
    } else {
        $naam = test_input($_POST["naam"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "Zonder een mailadres kunnen wij uw mail niet beantwoorden";
    } else {
        $email = test_input($_POST["email"]);
    }

}

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

if (isset($_POST['submit']) && !empty($_POST['email']) && !empty($_POST['naam'])) {
    $naam      = $_POST['naam'];
    $email     = $_POST['email'];
    $onderwerp = "Contactformulier ingevuld door $naam";
    $bericht   = $_POST['bericht'];
    $CS        = "[email protected]";
    $afzender  = "Googla BV";

    $headers = 'From: GoogleBV <[email protected]>' . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
    mail($CS, $onderwerp, $bericht, $headers);

}


?>

Now it checks if the form is submitted and the username/email are not empty.

Ad
source: stackoverflow.com
Ad