Twitter Bootstrap Contact Form Tutorial using PHP with Validations

yotube
0

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>
Read Also:

Now you might have a better understanding of using php to build twitter bootstrap contact form. Hopefully you have enjoyed reading this tutorial. Please don't forget to share it on social networks.

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top