Building a Contact Form to Demonstrate PHP Form Validation using Array

A lot of us come across forms of different types as we surf the internet such as registration, login, contact and survey forms.
In these forms are rules that the user must conform to in order to successfully submit the form.
In the event that the user enters an invalid value(s) to the form field, the website will validate the entered data. If deem valid, the data will be sent to the server for processing otherwise, the data get rejected and an error message thrown to the user.

Whenever I am developing a simple PHP application that involves collecting information from end-users via forms, I use an array to store the form generated errors, afterward iterate over the array and output the error(s).

If the array contains no errors, it means nothing went awry hence the form is finally sent to the server for processing.

To understand how validation in PHP using array is done, let’s build a simple contact form.

Create the contact-form class and add the error array property.


class Contact_form {

	private $form_errors = array();

The property <span class="spanz">$form_errors</span> will be the error array that will contain all errors generated from the contact-form.

The <span class="spanz">__construct()</span> magic method below call the <span class="spanz">validate_form()</span> to validate the form values, display the form error(s) if it exist, call the <span class="spanz">send_email()</span> method to send the email and finally  display the contact form.

function __construct() {
        if (isset($_POST['form-submitted'])) {

            // call validate_form() to validate the form values
            $this->validate_form($_POST['your-name'], $_POST['your-email'], $_POST['your-subject'], $_POST['your-message']);

            // display form error if it exist
            if (is_array($this->form_errors) && count($this->form_errors) > 0) {
                foreach ($this->form_errors as $error) {
                    echo '<div>';
                    echo '<strong>ERROR</strong>:';
                    echo $error . '<br/>';
                    echo '</div>';

            $this->send_email($_POST['your-name'], $_POST['your-email'], $_POST['your-subject'], $_POST['your-message']);


Below is the code for the validate_form method that validates the entered form data. If any of the form data fail the validation test, the error message is appended to our $form_errors property array.

function validate_form($name, $email, $subject, $message) {

        // If any field is left empty, add the error message to the error array
        if (empty($name) || empty($email) || empty($subject) || empty($message)) {
            array_push($this->form_errors, 'No field should be left empty');

        // if the name field isn't alphabetic, add the error message
        if (strlen($name) < 4) {
            array_push($this->form_errors, 'Name should be at least 4 characters');
        // Check if the email is valid
        if (!filter_var($email, FILTER_SANITIZE_EMAIL)) {
            array_push($this->form_errors, 'Email is not valid');

Read the comment in the code to understand how the form data are validated.

Below is the code for the static form() method that displays the contact-form HTML form.

public static function form() {
        <form action="<?php echo $_SERVER&#91;'REQUEST_URI'&#93;; ?>" method="post">
                Your Name (required) <br/>
                <input type="text" name="your-name" value="<?php echo ( isset($_POST&#91;"your-name"&#93;) ? $_POST&#91;"your-name"&#93; : null ); ?>" size="40" />
                Your Email (required) <br/>
                <input type="text" name="your-email" value="<?php echo ( isset($_POST&#91;"your-email"&#93;) ? $_POST&#91;"your-email"&#93; : null ); ?>" size="40" />
                Subject (required) <br/>
                <input type="text" name="your-subject" value="<?php echo ( isset($_POST&#91;"your-subject"&#93;) ? $_POST&#91;"your-subject"&#93; : null ); ?>" size="40" />
                Your Message (required) <br/>
                <textarea rows="10" cols="35" name="your-message"><?php echo ( isset($_POST&#91;"your-message"&#93;) ? $_POST&#91;"your-message"&#93; : null ); ?></textarea>
            <p><input type="submit" name="form-submitted" value="Send"></p>

The <span class="spanz">send_email()</span> method handles the sending of the email.
Note: The email is only sent if the contact-form generated no errors i.e. ensure the error array (<strong>$form_errors</strong>) contain no error.

function send_email($name, $email, $subject, $message) {

        // Ensure the error array ($form_errors) contain no error
        if (count($this->form_errors) < 1) {

            // sanitize form values
            $name = strip_tags($name);
            $email = strip_tags($email);
            $subject = htmlspecialchars($subject);
            $message = htmlspecialchars($message);

            // mail recipient email address
            $to = '';

            $headers = "From: $name <$email>" . "\r\n";

            // If email has been process for sending, display a success message
            if (mail($to, $subject, $message, $headers))
                echo '<div style="background: #3b5998; color:#fff; padding:2px;margin:2px">';
            echo 'Thanks for contacting me, expect a response soon.';
            echo '</div>';

Take note: the $to variable in the code above stores the email address of the recipient.

We are finally done coding the contact form. To use the contact form, instantiate the class as follows:

new Contact_form;

Below is a screenshot of the contact form validation in action.

Contact form validation in action

Grab the Contact-form PHP class from my Github repository.

About Agbonghama Collins

Agbonghama Collins is a webdeveloper and an internet geek. I love writing and sharing the little idea & information i know. Hope you enjoyed my Article.

Follow me on Twitter, add him on Facebook or on Google+