Contact Form

Bootstrap contact form

Note: We are transitioning MDB4 to a legacy version and focusing on developing MDB5. While we'll continue to support for the transition period, we encourage you to migrate to MDB5. We're offering a huge discount on MDB5 PRO to help with your transition, enabling you to leverage the full potential of the latest version. You can find more information here.
upgrade with discount

Today we will learn how to easily create beautiful contact forms using the Bootstrap framework, PHP and JavaScript. You don't need specialist knowledge to achieve this, just follow this tutorial. If you have any questions, please do not hesitate to post a question on our support forum.

What will I learn?

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

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


Bootstrap Contact Form

An example contact form is given below:

Contact us

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

  • San Francisco, CA 94126, USA

  • + 01 234 567 89

  • contact@mdbootstrap.com

        
            

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

              <!--Section heading-->
              <h2 class="h1-responsive font-weight-bold text-center my-4">Contact us</h2>
              <!--Section description-->
              <p class="text-center w-responsive mx-auto mb-5">Do you have any questions? Please do not hesitate to contact us directly. Our team will come back to you within
                  a matter of hours to help you.</p>

              <div class="row">

                  <!--Grid column-->
                  <div class="col-md-9 mb-md-0 mb-5">
                      <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 mb-0">
                                      <input type="text" id="name" name="name" class="form-control">
                                      <label for="name" class="">Your name</label>
                                  </div>
                              </div>
                              <!--Grid column-->

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

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

                          <!--Grid row-->
                          <div class="row">
                              <div class="col-md-12">
                                  <div class="md-form mb-0">
                                      <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" rows="2" class="form-control md-textarea"></textarea>
                                      <label for="message">Your message</label>
                                  </div>

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

                      </form>

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

                  <!--Grid column-->
                  <div class="col-md-3 text-center">
                      <ul class="list-unstyled mb-0">
                          <li><i class="fas fa-map-marker-alt fa-2x"></i>
                              <p>San Francisco, CA 94126, USA</p>
                          </li>

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

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

              </div>

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

        
        
    

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

Note!

Within this tutorial we are using the Material Design for Bootstrap library, you can download it for free from here. Without the library the form will still work, however it may look and behave differently. It's recommended to use this library along with the tutorial.


Connecting your contact form to email using PHP

Create a new file called mail.php within the same folder as the contact form and place within it the 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 youremail@here.com with your email address and it's done. Remember that in order for the script to work you will need to keep it on PHP-supporting server such as Apache.

You can download the source code file from here.


Javascript validation (client-side validation)

Our form now works fine. However currently if the user makes a mistake by clicking send without filling in the form first, this will result in sending an empty email. The other potential problem is that user might make a mistake in his email address so he would never get a response from us.

In order to apply validation we have to change the code of our form. So first change the existing line in index.html file

        
            

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

        
        
    

with the following line, which instead of directly submitting the form will call our validation function:

        
            

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

        
        
    

Now we have to create our validation function. Add the following code after (below) the script has finished importing the bootstrap JavaScript files:

        
            

          function validateForm() {
            var name =  document.getElementById('name').value;
            if (name == "") {
                document.querySelector('.status').innerHTML = "Name cannot be empty";
                return false;
            }
            var email =  document.getElementById('email').value;
            if (email == "") {
                document.querySelector('.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.querySelector('.status').innerHTML = "Email format invalid";
                    return false;
                }
            }
            var subject =  document.getElementById('subject').value;
            if (subject == "") {
                document.querySelector('.status').innerHTML = "Subject cannot be empty";
                return false;
            }
            var message =  document.getElementById('message').value;
            if (message == "") {
                document.querySelector('.status').innerHTML = "Message cannot be empty";
                return false;
            }
            document.querySelector('.status').innerHTML = "Sending...";
          }

        
        
    

You can download the source file from here.


PHP validation (server-side validation)

Since user can easily disable Javascript on his side, it's very important to also validate the submitted form on the server side. In order to add similar validation as we did in the previous point, update the mail.php file by adding the 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'];
  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 = "youremail@here.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 an email without reloading the page using AJAX

Our contact form is working correctly, however the user experience leaves much to be desired. Instead of reloading the page, we would like to send contact form on the same page. Let’s replace following JavaScript code in index.html file:

        
            

  document.getElementById('status').innerHTML = "Sending...";
  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.message);
      if (data.code) //If mail was sent successfully, reset the form.
        $('#contact-form').closest('form').find("input[type=text], textarea").val("");
    },
    error: function (jqXHR, textStatus, errorThrown) {
      $('#status').text(jqXHR);
    }
  });

        
        
    

We also need to adjust our PHP code. Instead of sending a simple string with the message, we will send a slightly more complex object which will contain both status and the message. If everything goes fine and the email was successfully sent. We will return status 1 and clean our form to make sure that user does not send it multiple times. In case of validation errors we will return 0 and keep the data within the form.

        
            

<? php
  $name = $_POST['name'];
  $email = $_POST['email'];
  $message = $_POST['message'];
  $subject = $_POST['subject'];
  header('Content-Type: application/json');
  if ($name === '') {
    print json_encode(array('message' => 'Name cannot be empty', 'code' => 0));
    exit();
  }
  if ($email === '') {
    print json_encode(array('message' => 'Email cannot be empty', 'code' => 0));
    exit();
  } else {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      print json_encode(array('message' => 'Email format invalid.', 'code' => 0));
      exit();
    }
  }
  if ($subject === '') {
    print json_encode(array('message' => 'Subject cannot be empty', 'code' => 0));
    exit();
  }
  if ($message === '') {
    print json_encode(array('message' => 'Message cannot be empty', 'code' => 0));
    exit();
  }
  $content = "From: $name \nEmail: $email \nMessage: $message";
  $recipient = "youremail@here.com";
  $mailheader = "From: $email \r\n";
  mail($recipient, $subject, $content, $mailheader) or die("Error!");
  print json_encode(array('message' => 'Email successfully sent!', 'code' => 1));
  exit();
?>


        
        
    

Voila! Now our contact form works without reloading.

You can download the source file from here.


Anti-spam

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

The simplest (but also the weakest) way to secure a contact form is to add a custom field, then ask the customer to fill it in a certain way, and submit the form only if the entered value is correct. Real humans will easily perform this task, 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 a more sophisticated solution read about Google's reCAPTCHA service


Other inputs

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

Checkbox

HTML code:

        
            

          <div class="form-check">
            <input type="checkbox" class="form-check-input" name="updates" id="updates" value="1">
            <label for="updates" class="form-check-label">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 to know about us?</strong></h5>
              <div class="form-check">
                  <input type="checkbox" class="form-check-input" name="channel[]" id="checkbox1" value="nl">
                  <label for="checkbox1" class="form-check-label">Newsletter</label>
              </div>

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

              <div class="form-check">
                  <input type="checkbox" class="form-check-input" name="channel[]" id="checkbox3" value="ot">
                  <label for="checkbox3" class="form-check-label">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/option buttons

What is your preferred contact method?

HTML code:

        
            

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

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

            <div class="form-check mb-3">
                <input class="form-check-input" type="radio" id="radio3" name="cmethod" value="post">
                <label class="form-check-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