0

I need to create validation for this form, and I don't know how to do it right.

    <?php
$errName = '';
$errEmail = '';
$errMessage = '';
$result = '';

if (isset($_POST["submit"])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'simply@email.tld';
    $to = 'again@email.tld';
    $subject = 'Form';

    $body = "Name: $name \n E-mail: $email \n Message: $message";
}

if (!$_POST['name']) {
    $errName = 'Write Name here.';
}

if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $errEmail = 'Write correct e-mail';
}

if (!$_POST['message']) {
    $errMessage = 'Write your message';
}

if (!$errName && !$errEmail && !$errMessage) {
    if (mail ($to, $subject, $body, $from)) {
        $result = "<div style='color:white;font-size:15px;font-weight:700;'>Your message has been sent.</div>";
    } else {
        $result = "<div style='color:red;font-size:15px;font-weight:700;'>Your message has not been sent, try again!</div>";
    }

}

?>

The form works right but if as example I won't write one thing there is no error, message just isn't sent. Any ideas what's wrong?

d4vinc1
  • 25
  • 4
  • 2
    Well first things first. Validate the data BEFORE loading it into variables – RiggsFolly Dec 20 '16 at 18:33
  • What do you mean? – d4vinc1 Dec 20 '16 at 18:34
  • If you want to see your errors Add [error reporting](http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php/845025#845025) to the top of your file(s) _while testing_ right after your opening PHP tag for example ` – RiggsFolly Dec 20 '16 at 18:42

1 Answers1

0

The problem I see with your original code is that the variables that contain the error message ($errName, $errEmail, $errMessage) aren't ever echo'd anywhere. They simply get checked if they contain any content and if none of them do then the mail function is called, otherwise nothing.

I believe a better approach to this would be to use a try/catch block. Your approach continues checking for valid variables even if a previous variable has already failed a check and the mail is already going to be prevented because of it. In this application, a couple extra easy checks aren't going to amount to anything significant, resource-wise. But in a larger application it's a good idea to not waste resources if you already know something is going to fail.

I've rewritten your code using the suggested try/catch block.

<?php

if (isset($_POST["submit"])) {

    $name       = (string) $_POST['name'];
    $email      = (string) $_POST['email'];
    $message    = (string) $_POST['message'];

    $from       = 'simply@email.tld';
    $to         = 'again@email.tld';
    $subject    = 'Form';

    $body = "Name: $name \n E-mail: $email \n Message: $message";

    try {

        if (!$name) {

            throw new Exception('Write Name here.');

        }

        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {

            throw new Exception('Write correct e-mail');

        }

        if (!$message) {

            throw new Exception('Write your message');

        }

        if (mail ($to, $subject, $body, $from)) {

            $result = "<div style='color:white;font-size:15px;font-weight:700;'>Your message has been sent.</div>";

        } else {

            throw new Exception("Your message has not been sent, try again!");

        }

    } catch(Exception $e){

        $result = "<div style='color:red;font-size:15px;font-weight:700;'>" . $e->getMessage() . "</div>";

    }

    echo $result;

}

?>

If a variable doesn't pass one of your checks, a new Exception is thrown with the applicable error message. This stops further execution in the try block and moves execution to the catch block. The $result variable gets filled with your styled error message, which gets echo'd at the end. Likewise, if the mail is successfully sent, the $result variable gets filled with the success message which gets echo'd.

ffork
  • 348
  • 2
  • 4