Login with:


Or:


Not a member? Sign Up

Forgot Password?

Signup with:


Or:


Already have an account? Log in

Bootstrap Contact Form

Today we will learn how to easily create beautiful contact form using Bootstrap framework, PHP and JavaScript. You don't need specialist knowledge to achieve that, just follow this tutorial and in case of question do not hesitate to post a question at our support forum.

What will I learn?

  1. How to create HTML contact form using Bootstrap
  2. How to connect contact form to your email using PHP
  3. How to validate entered fields using JavaScript and PHP
  4. How to send contact form without reloading page using AJAX
  5. How to create anti spam mechanism
  6. How to use different inputs

At the end of the tutorial I will also show you few different contact form styles as a inspiration and ready to use snippets. If you don't want to follow tutorial, just need working solution you can download final files from our github repository here.


Bootstrap Contact Form

This how our contact form will look like:

Contact us

Do you have any questions? Please do not hesitate to contact us directly. Our team will come back to you within matter of hours to help you.

  • San Francisco, CA 94126, USA

  • + 01 234 567 89

  • contact@mdbootstrap.com

Copy and paste following code into your file (i.e. index.html):

                
<!--Section: Contact v.2-->
<section class="section">

    <!--Section heading-->
    <h2 class="section-heading h1 pt-4">Contact us</h2>
    <!--Section description-->
    <p class="section-description">Do you have any questions? Please do not hesitate to contact us directly. Our team will come back to you within matter of hours to help you.</p>

    <div class="row">

        <!--Grid column-->
        <div class="col-md-8 col-xl-9">
            <form id ="contact-form" name="contact-form" action="mail.php" method="POST">

                <!--Grid row-->
                <div class="row">

                    <!--Grid column-->
                    <div class="col-md-6">
                        <div class="md-form">
                            <div class="md-form">
                                <input type="text" id="name" name="name" class="form-control">
                                <label for="name" class="">Your name</label>
                            </div>
                        </div>
                    </div>
                    <!--Grid column-->

                    <!--Grid column-->
                    <div class="col-md-6">
                        <div class="md-form">
                            <div class="md-form">
                                <input type="text" id="email" name="email" class="form-control">
                                <label for="email" class="">Your email</label>
                            </div>
                        </div>
                    </div>
                    <!--Grid column-->

                </div>
                <!--Grid row-->

                <!--Grid row-->
                <div class="row">
                    <div class="col-md-12">
                        <div class="md-form">
                            <input type="text" id="subject" name="subject" class="form-control">
                            <label for="subject" class="">Subject</label>
                        </div>
                    </div>
                </div>
                <!--Grid row-->

                <!--Grid row-->
                <div class="row">

                    <!--Grid column-->
                    <div class="col-md-12">

                        <div class="md-form">
                            <textarea type="text" id="message" name="message" class="md-textarea"></textarea>
                            <label for="message">Your message</label>
                        </div>

                    </div>
                </div>
                <!--Grid row-->

            </form>

            <div class="center-on-small-only">
                <a class="btn btn-primary" onclick="document.getElementById('contact-form').submit();">Send</a>
            </div>
            <div class="status" id="status"></div>
        </div>
        <!--Grid column-->

        <!--Grid column-->
        <div class="col-md-4 col-xl-3">
            <ul class="contact-icons">
                <li><i class="fa fa-map-marker fa-2x"></i>
                    <p>San Francisco, CA 94126, USA</p>
                </li>

                <li><i class="fa fa-phone fa-2x"></i>
                    <p>+ 01 234 567 89</p>
                </li>

                <li><i class="fa fa-envelope fa-2x"></i>
                    <p>contact@mdbootstrap.com</p>
                </li>
            </ul>
        </div>
        <!--Grid column-->

    </div>

</section>
<!--Section: Contact v.2-->
            

Connect your contact form to email using PHP

Create new file called mail.php within the same folder as contact form and place following code:

                
<?php
if(isset( $_POST['name']))
  $name = $_POST['name'];
if(isset( $_POST['email']))
  $email = $_POST['email'];
if(isset( $_POST['message']))
  $message = $_POST['message'];
if(isset( $_POST['subject']))
  $subject = $_POST['subject'];

$content="From: $name \n Email: $email \n Message: $message";
$recipient = "youremail@here.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
echo "Email sent!";
?>
            

Now just replace youremaiil@here.com with your email address and it's done. Remember that in order to make script working you will need to keep it on server like Apache supporting PHP.

You can download source file from here.


Javascript validation (client side validation)

Our form is working fine, however currently user by mistake click send without filling form which will result in sending empty email. The other thread is that user will make a mistake in his email address so, he will never get response from us.

In order apply validation we have to change code of our form, change existing line

                
<a class="btn btn-primary" onclick="document.getElementById('contact-form').submit();">Send</a>
            

with following line, which instead of directly submit form will call our validating function:

                
<a class="btn btn-primary" onclick="validateForm()">Send</a>
            

Now we have to create our validation function. Add following code after (below) importing bootstrap js files:

                
<script>
function validateForm() {
    var name =  document.getElementById('name').value;
    if (name == "") {
        document.getElementById('status').innerHTML = "Name cannot be empty";
        return false;
    }
    var email =  document.getElementById('email').value;
    if (email == "") {
        document.getElementById('status').innerHTML = "Email cannot be empty";
        return false;
    } else {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if(!re.test(email)){
            document.getElementById('status').innerHTML = "Email format invalid";
            return false;
        }
    }
    var subject =  document.getElementById('subject').value;
    if (subject == "") {
        document.getElementById('status').innerHTML = "Subject cannot be empty";
        return false;
    }
    var message =  document.getElementById('message').value;
    if (message == "") {
        document.getElementById('status').innerHTML = "Message cannot be empty";
        return false;
    }
    document.getElementById('status').innerHTML = "Sending...";
    document.getElementById('contact-form').submit();

}
</script>
            

You can download source file from here.


PHP validation (server side validation)

Since user can easily disable JS on his side, it's very important to also validate submitted form on server side. In order to add similar validation as we in previous point add update mail.php file with following content:

                
<?php
if(isset( $_POST['name']))
  $name = $_POST['name'];
if(isset( $_POST['email']))
  $email = $_POST['email'];
if(isset( $_POST['message']))
  $message = $_POST['message'];
if(isset( $_POST['subject']))
  $subject = $_POST['subject'];
if ($name === ''){
  echo "Name cannot be empty.";
  die();
}
if ($email === ''){
  echo "Email cannot be empty.";
  die();
} else {
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo "Email format invalid.";
    die();
  }
}
if ($subject === ''){
  echo "Subject cannot be empty.";
  die();
}
if ($message === ''){
  echo "Message cannot be empty.";
  die();
}
$content="From: $name \nEmail: $email \nMessage: $message";
$recipient = "dawidadach@gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
echo "Email sent!";
?>
            

You can download source file from here.


Sending email without reloading page using AJAX

Our contact is working correct, however user experience leaves much to be desired. Instead of reloading page we would like to send contact form on the same page. Lets' replace following code of JS:

                
document.getElementById('contact-form').submit();
            

with his JQuery snippet:

                
formData = {
    'name'     : $('input[name=name]').val(),
    'email'    : $('input[name=email]').val(),
    'subject'  : $('input[name=subject]').val(),
    'message'  : $('textarea[name=message]').val()
};


$.ajax({
    url : "mail.php",
    type: "POST",
    data : formData,
    success: function(data, textStatus, jqXHR)
    {
        $('#status').text(data);
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        $('#status').text(jqXHR);
    }
});
            

Voila! Now our contact form works without reloading.

You can download source file from here.


Anti spam

Once you create your contact form it's worth to add anti spam mechanism. Unfortunately, there are hundreds of thousands spam bots browsing Internet in every second looking for unsecured forms and submitting them. How they work? They simply fill typical inputs like name or email and automatically submitting form. In the best case you will get occasional frustrating spam messages. In worst they can get down your hosting by submitting contact form hundreds time in a second.

The simplest (but also the weakest) way to secure your contact form is to add custom field and ask customer to fill it in certain way and and submit the form only if value is correct. Real human will easily solve the issue, but bots most probably won't be able to pass the check.

Other questions

  • Q: How many eyes does a typical person have? (ex: 1) A: 2
  • Q: How many legs on a typical dog? (ex: 5) A: 4
  • Q: How many units in a dozen? (ex: 11) A: 12
  • Q: Name of the actor Di Caprio? (ex: Rafaelo) A:Leonardo
  • Q: How many days in a week? (ex: 8) A: 7
  • Q: How many days in July? (ex: 28) A: 31

If you want more sophisticated solution read about Google reCAPTCHA service


Other inputs

We've already used text inputs as well as text area for larger piece of text but there are more useful input types we can use to enhance our contact form.

Checkbox

HTML code:

                
<div class="form-group">
    <input type="checkbox" name="updates" id="updates" value="1">
    <label for="updates">Notify me about new updates</label>
</div>
            

JS code:

                
formData = {
    'name'     : $('input[name=name]').val(),
    'email'    : $('input[name=email]').val(),
    'subject'  : $('input[name=subject]').val(),
    'message'  : $('textarea[name=message]').val(),
    'updates'  : $('input:checkbox[name=updates]').is(':checked')
};
            

PHP code:

                
if(isset( $_POST['updates']))
  $updates = $_POST['updates'];
            

Multiple checkboxes

How did you get to know about us?

HTML code:

                
<div id="feedback">
<h5><strong>How did you get know about us?</strong></h5>
<div class="form-group">
    <input type="checkbox" name="channel[]" id="checkbox1" value="nl">
    <label for="checkbox1">Newsletter</label>
</div>

<div class="form-group">
    <input type="checkbox" name="channel[]" id="checkbox2" value="ad">
    <label for="checkbox2">Advertisement</label>
</div>

<div class="form-group">
    <input type="checkbox" name="channel[]" id="checkbox3" value="ot">
    <label for="checkbox3">Other</label>
</div>
</div>

JS code:

                
var channels = [];
$('#feedback input:checked').each(function() {
    channels.push(this.value);
});

formData = {
    'name'     : $('input[name=name]').val(),
    'email'    : $('input[name=email]').val(),
    'subject'  : $('input[name=subject]').val(),
    'message'  : $('textarea[name=message]').val(),
    'channel'  : channels
};
            

PHP code:

                
if(isset( $_POST['updates'])){
  foreach ($_POST['channel'] as $value) {
      //loop through all checked checkboxes and do logic
  }
}
            

Radio

Preferred contact method?

HTML code:

                
<div class="form-group">
    <input type="radio" id="radio1" name="cmethod" value="phone" checked>
    <label for="radio1">Phone</label>
</div>

<div class="form-group">
    <input type="radio" id="radio2"  name="cmethod" value="mail">
    <label for="radio2">Email</label>
</div>

<div class="form-group">
    <input type="radio" id="radio3"  name="cmethod" value="post">
    <label for="radio3">Post</label>
</div>

JS code:

                
formData = {
    'name'     : $('input[name=name]').val(),
    'email'    : $('input[name=email]').val(),
    'subject'  : $('input[name=subject]').val(),
    'message'  : $('textarea[name=message]').val(),
    'cmethod'  : $('input:radio[name=cmethod]:checked').val()
};
            

PHP code:

                
if(isset( $_POST['cmethod']))
$updates = $_POST['cmethod'];
            

Other contact form samples

CONTACT US

Contact Us

You can find more examples of Contact Forms in the links below:

Form components Contact sections