Twitter Bootstrap Contact Form Tutorial using PHP with Validations

On 2/25/2015

Contact Forms are one of the key elements of websites that allows the visitors to communicate to the site owners through mails. Since Bootstrap is only a front end framework we should use server side script like php to make the contact form fully functional. Here in this tutorial, we'll see how to build a bootstrap contact form using PHP along with form validations. We are not going to use any java script library for validations as all the validations will be done in the server side for maximum security.

The contact form we are going to build is a clean minimalistic design that contains input fields for name, email, subject and message. Once the user fills out the form and submits it, all user input will be checked for validation errors. If there is any error, it will be displayed in the form else a mail will be sent and notified to the user.

Build Twitter Bootstrap Contact Form

First let's write the required html markup to build the contact form in bootstrap. Creating web forms with bootstrap is a breeze with all that built-in classes available. This twitter bootstrap contact form is a responsive one which means it shrinks to fit well in mobile screen. Here goes the html markup for the form.

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3 well">
            <form role="form" class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactform">
            <fieldset>
                <legend>Bootstrap Contact Form</legend>

                <div class="form-group">
                    <div class="col-md-12">
                        <label for="txt_name" class="control-label">Name</label>
                    </div>
                    <div class="col-md-12">
                        <input class="form-control" name="txt_name" placeholder="Your Full Name" type="text" value="<?php if($error) echo $name; ?>" />
                        <span class="text-danger"><?php if (isset($name_error)) echo $name_error; ?></span>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-12">
                        <label for="txt_email" class="control-label">Email ID</label>
                    </div>
                    <div class="col-md-12">
                        <input class="form-control" name="txt_email" placeholder="Your Email ID" type="text" value="<?php if($error) echo $fromemail; ?>" />
                        <span class="text-danger"><?php if (isset($fromemail_error)) echo $fromemail_error; ?></span> 
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-12">
                        <label for="txt_subject" class="control-label">Subject</label>
                    </div>
                    <div class="col-md-12">
                        <input class="form-control" name="txt_subject" placeholder="Your Subject" type="text" value="<?php if($error) echo $subject; ?>" />
                        <span class="text-danger"><?php if (isset($subject_error)) echo $subject_error; ?></span>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-12">
                        <label for="txt_msg" class="control-label">Message</label>
                    </div>
                    <div class="col-md-12">
                        <textarea class="form-control" name="txt_msg" rows="4" placeholder="Your Message"><?php if($error) echo $message; ?></textarea>
                        <span class="text-danger"><?php if (isset($message_error)) echo $message_error; ?></span>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-12">
                        <input name="submit" type="submit" class="btn btn-primary" value="Send" />
                    </div>
                </div>
            </fieldset>
            </form>
            <?php if (isset($alertmsg)) { echo $alertmsg; } ?>
        </div>
    </div>
</div>

As you can see in the above markup, bootstrap css classes for form have been used along with the html elements. We make sure to center align the form to the view port (screen) using the classes "col-md-6" and "col-md-offset-3". Adding "form-horizontal" class to the html form element will make use of the bootstrap grid system to align the labels and the form group elements in a horizontal layout. Also we have used bootstrap's role="form" attribute for easier accessibility.

Bootstrap Form Validation Class

We have used <span> element with "text-danger" class below each form input to display the validation error. This displays the error messages in red color below the input field in case there is any error. Additionally we also repopulate the form fields with the user input using the "value" attribute in case of validation error like this.

bootstrap-php-contact-form-validation-errors

Next we'll move on to php script where we collect the contact form data and send mail.

Recommended Read: How to Autocomplete Textbox from MySQL Database in PHP and jQuery

Recommended Read: How to Connect MySQL Database in PHP

PHP Script for Bootstrap Contact Form

Let's set an error flag as false to indicate of no validation error in the contact form data initially.

<?php
//set validation error flag as false
$error = false;
?>

Next get the submitted form data and store in variables.

<?php
//check if form is submitted
if (isset($_POST['submit']))
{
    $name = trim($_POST['txt_name']);
    $fromemail = trim($_POST['txt_email']);
    $subject = trim($_POST['txt_subject']);
    $message = trim($_POST['txt_msg']);
}
?>

The function trim() will cut down the preceding and trailing white spaces of the input.

Next check for the validation error in the posted data.

<?php
if (isset($_POST['submit']))
{
    ...
    
    //name can contain only alpha characters and space
    if (!preg_match("/^[a-zA-Z ]+$/",$name))
    {
        $error = true;
        $name_error = "Please Enter Valid Name";
    }
    if(!filter_var($fromemail,FILTER_VALIDATE_EMAIL))
    {
        $error = true;
        $fromemail_error = "Please Enter Valid Email ID";
    }
    if(empty($subject))
    {
        $error = true;
        $subject_error = "Please Enter Your Subject";
    }
    if(empty($message))
    {
        $error = true;
        $message_error = "Please Enter Your Message";
    }
}
?>

Here we check for the name field to contain only alpha characters and space. Using the regular expression with the function preg_match() will do the job. If you want to learn to more about using regular expressions, take a look at this article on using regular expressions for form validations in php.

Next we check for valid email id using the filter_var() function. Using the token "FILTER_VALIDATE_EMAIL" will validate the given email id.

For the subject and message field we check if they are empty or not.

Finally we send the mail if there is no validation error.

<?php
if (isset($_POST['submit']))
{
    ...

    if (!$error)
    {
        //send mail
        $toemail = "me@mydomain.com";
        $subject = "Enquiry from Visitor " . $name;
        $body = "Here goes your Message Details: \n\n Name: $name \n From: $fromemail \n Message: \n $message";
        $headers = "From: $fromemail\n";
        $headers .= "Reply-To: $fromemail";

        if (mail ($toemail, $subject, $body, $headers))
            $alertmsg  = '<div class="alert alert-success text-center">Message sent successfully.  We will get back to you shortly!</div>';
        else
            $alertmsg = '<div class="alert alert-danger text-center">There is error in sending mail.  Please try again later.</div>';
    }
}
?>

Note: In the above code change the "$toemail" value to the email-id you want to receive the mails.

We use the php mail() function to send the email. If mail is sent without any error we display a success message to the user like this.

bootstrap-3-contact-form-send-mail-message

In case the mail is not sent due to some technical error we notify a failure message to the user like this.

bootstrap-3-contact-form-error-message

Here is the complete php bootstrap contact form code.

<?php 
    //set validation error flag as false
    $error = false;
    //check if form is submitted
    if (isset($_POST['submit']))
    {
        $name = trim($_POST['txt_name']);
        $fromemail = trim($_POST['txt_email']);
        $subject = trim($_POST['txt_subject']);
        $message = trim($_POST['txt_msg']);

        //name can contain only alpha characters and space
        if (!preg_match("/^[a-zA-Z ]+$/",$name))
        {
            $error = true;
            $name_error = "Please Enter Valid Name";
        }
        if(!filter_var($fromemail,FILTER_VALIDATE_EMAIL))
        {
            $error = true;
            $fromemail_error = "Please Enter Valid Email ID";
        }
        if(empty($subject))
        {
            $error = true;
            $subject_error = "Please Enter Your Subject";
        }
        if(empty($message))
        {
            $error = true;
            $message_error = "Please Enter Your Message";
        }
        if (!$error)
        {
            //send mail
            $toemail = "me@mydomain.com";
            $subject = "Enquiry from Visitor " . $name;
            $body = "Here goes your Message Details: \n\n Name: $name \n From: $fromemail \n Message: \n $message";
            $headers = "From: $fromemail\n";
            $headers .= "Reply-To: $fromemail";

            if (mail ($toemail, $subject, $body, $headers))
                $alertmsg  = '<div class="alert alert-success text-center">Message sent successfully.  We will get back to you shortly!</div>';
            else
                $alertmsg = '<div class="alert alert-danger text-center">There is error in sending mail.  Please try again later.</div>';
        }
    }
?>

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap 3 Contact Form Example</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport" >
    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3 well">
            <form role="form" class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactform">
            <fieldset>
                <legend>Bootstrap Contact Form</legend>

                <div class="form-group">
                    <div class="col-md-12">
                        <label for="txt_name" class="control-label">Name</label>
                    </div>
                    <div class="col-md-12">
                        <input class="form-control" name="txt_name" placeholder="Your Full Name" type="text" value="<?php if($error) echo $name; ?>" />
                        <span class="text-danger"><?php if (isset($name_error)) echo $name_error; ?></span>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-12">
                        <label for="txt_email" class="control-label">Email ID</label>
                    </div>
                    <div class="col-md-12">
                        <input class="form-control" name="txt_email" placeholder="Your Email ID" type="text" value="<?php if($error) echo $fromemail; ?>" />
                        <span class="text-danger"><?php if (isset($fromemail_error)) echo $fromemail_error; ?></span> 
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-12">
                        <label for="txt_subject" class="control-label">Subject</label>
                    </div>
                    <div class="col-md-12">
                        <input class="form-control" name="txt_subject" placeholder="Your Subject" type="text" value="<?php if($error) echo $subject; ?>" />
                        <span class="text-danger"><?php if (isset($subject_error)) echo $subject_error; ?></span>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-12">
                        <label for="txt_msg" class="control-label">Message</label>
                    </div>
                    <div class="col-md-12">
                        <textarea class="form-control" name="txt_msg" rows="4" placeholder="Your Message"><?php if($error) echo $message; ?></textarea>
                        <span class="text-danger"><?php if (isset($message_error)) echo $message_error; ?></span>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-12">
                        <input name="submit" type="submit" class="btn btn-primary" value="Send" />
                    </div>
                </div>
            </fieldset>
            </form>
            <?php if (isset($alertmsg)) { echo $alertmsg; } ?>
        </div>
    </div>
</div>
</body>
</html>

Recommended Read: Build Twitter Bootstrap Carousel Image Slider

Recommended Read: Creating Bootstrap Responsive Navigation Menu Tutorial

Now you might have a better understanding of using php to build twitter bootstrap contact form. Hopefully you have enjoyed reading this tutorial.

15 comments:

  1. I have a couple questions for you,

    what do i have to save the php code as to link it to my form.

    and why is the value displaying in my text field, instead of my place holder?
    in the text field it displays

    ReplyDelete
    Replies

    1. Hi, for question #1, I have included the php script in the same contact form and used "action= echo $_SERVER['PHP_SELF'];" which loads the same file when the form is submitted. Else you can save the php code as a separate file say "sendmail.php" and link it to the form "action" attribute.

      For question #2, sorry can you be more precise?

      Delete
  2. Thanks a lot. It was really helpful.

    ReplyDelete
  3. thank you very much, I have adapted your code to my page, all credits to you.

    ReplyDelete
  4. Thanks so much for this! I've never worked with PHP before, so this made it really easy for me.

    I was wondering if there's a way to keep the page on the contact form after the email goes through. Right now after I click submit as a user, it kicks me back to the top of the page and I have to scroll back down to see the successful submission panel. I'd love for users to just instantly see if their message succeeded or failed.

    ReplyDelete
    Replies
    1. Welcome Kelsey:) You can display the success msg at the top of the form so that it will be seen the fold.

      Just move the line,
      <?php if (isset($alertmsg)) { echo $alertmsg; } ?>
      to above the opening form tag (<form ...)

      Cheers.

      Delete
    2. I have done it, but whenever I submit the form with all fields or with incorrect field, it direct me to the top of the page... Please help.

      Delete
  5. I would never use PHP_SELF : http://www.mc2design.com/blog/article/serverphp_self-can-not-be-trusted-but-there-are-safe-alternatives

    ReplyDelete
  6. Why the hell does this ["] show up in my text field?

    ReplyDelete
  7. I adopted the page for my own website - The form works which is great so thank you.

    There is a problem,

    my two pages are both PHP.

    So Contact.php (that's the page with my form in it)
    html_form_send.php (that has the validation)

    The form is sending a message but it's redirecting us to the html_form_send.php page instead of showing me "message sent successfully/ there is an error" - any help?

    ReplyDelete
  8. It works beautifully - the error I made was having the PHP in a separate file and then referencing it in the action. Sticking to PHP self is the best solution. :) Thank you very much for this.

    ReplyDelete
  9. Thanks for this.

    Should the code be:

    to make it more secure?

    Getting my info from: http://www.w3schools.com/php/php_form_validation.asp about half way down the page.

    ReplyDelete

Contact Form

Name

Email *

Message *