Search code examples
phphtmlcssvalidationcontact-form

How to validate contact form when form is coded in html document?


I have a contact form that I wrote in the html document and this then is executed by an external php file. How do I validate it? All tutorials that I've looked at have shown the validation and the html form in the actual php file and so how can my validation be accomplished?

HTML5:

<form id="form-area" action="email-processor.php" method="POST">
    <div id="name-area"><p>Name (required)</p><input class="form-input" type="text" name="name"></div>
    <div id="email-area"><p>Email (required)</p> <input class="form-input" type="text" name="email"></div>
    <div id="phone-area"><p>Telephone</p> <input class="form-input" type="text" name="phone"></div>
    <div id="msg-area"><p>Message</p><textarea id="msg-input" name="message" rows="6" cols="25"></textarea><br /></div>
    <input id="sendbtn" type="submit" value="Send">
</form>

PHP:

<?php 
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $formcontent="From: $name \n Phone Number: $phone \n \n Message: \n \n$message";
    $recipient = "[email protected]"
    $subject = "Contact Form";
    $mailheader = "From: $email \r\n";

    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
    echo "Thank You!";
?>

Solution

  • You need to put required behind the input fields. If you want to make an email required as the standard format [email protected] instead simple text use type="email". For the telephone number you can use type="number" to allow numbers only, otherwise simply use text.

    NEW HTML

    <form id="form-area" action="email-processor.php" method="POST">
        <div id="name-area"><p>Name (required)</p><input type="text" class="form-input" type="text" name="name" required></div>
        <div id="email-area"><p>Email (required)</p> <input class="form-input" type="email" name="email" required></div>
        <div id="phone-area"><p>Telephone</p> <input class="form-input" type="number" name="phone" required></div>
        <div id="msg-area"><p>Message</p><textarea id="msg-input" name="message" rows="6" cols="25" required></textarea><br /></div>
        <input id="sendbtn" type="submit" value="Send">
    </form>