Search code examples
phpformsvalidationcontacts

Extend contact form validation PHP script with some error messages


Below is the code for a contact form validation script that I would like to extend.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: DaVv'; 
    $to = '[email protected]'; 
    $subject = 'The topic';

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if ($_POST['submit'] {               
        if (mail ($to, $subject, $body, $from)) { 
            echo '<p>Your message has been sent!</p>';
        } else { 
            echo '<p>Something went wrong, go back and try again!</p>'; 
        } 
    } else if ($_POST['submit'] {
        echo '<p>You answered the anti-spam question incorrectly!</p>';
    }
?>

I want to add one more message for user about email, something like: "Please enter valid email address." when, for example, they do not write "@". I know that this is included in html 5 but I'd like to make this w/o HTML5.


Solution

  • <?php
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $from = 'From: DaVv'; 
        $to = '[email protected]'; 
        $subject = 'The topic';
    
        $body = "From: $name\n E-Mail: $email\n Message:\n $message";
    
        if(isset($_POST['submit']))
        {
            if(filter_var($email, FILTER_VALIDATE_EMAIL) !== false)
            {               
                if(mail ($to, $subject, $body, $from))
                    echo '<p>Your message has been sent!</p>';
                else
                    echo '<p>Something went wrong, go back and try again!</p>'; 
            }
            else
                echo '<p>Wrong Email</p>';
    
        }
        else if(!isset($_POST['submit']))
            echo '<p>You answered the anti-spam question incorrectly!</p>';
    ?>