How to Create a Bootstrap Contact Form with Validation (Source Code)

Faraz

By Faraz -

Learn how to create a responsive Bootstrap contact form with validation to ensure data accuracy and enhance user experience. Follow our step-by-step guide and build your form today.


how to create a bootstrap contact form with validation.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Contact forms are essential elements of websites as they facilitate communication between website visitors and site owners. Whether it's for inquiries, feedback, or business opportunities, contact forms provide a convenient way for users to reach out. However, it's crucial to ensure that the data submitted through these forms is accurate and valid.

One common challenge with contact forms is user error when entering information. Users might forget to fill in required fields, provide incorrect email addresses, or make other mistakes that can hinder effective communication. This is where form validation comes into play.

Form validation is the process of verifying the accuracy and completeness of user-submitted data. It helps prevent erroneous or incomplete submissions by providing real-time feedback to users and highlighting any issues in their inputs. By incorporating form validation into a Bootstrap contact form, you can significantly enhance the user experience and improve data accuracy.

Bootstrap, a popular front-end framework, offers a wide range of pre-designed components and styles that can be easily implemented in web development projects. Leveraging Bootstrap's features, including its robust form components and validation classes, simplifies the process of creating a functional and visually appealing contact form with built-in validation.

In this tutorial, we will guide you step-by-step through the process of creating a Bootstrap contact form with validation. You will learn how to set up the HTML structure, apply Bootstrap classes and components, implement form validation, customize the form's appearance, and test its functionality. By the end, you'll have a fully functional contact form that enhances user experience and ensures accurate data submission.

Let's get started and create a seamless and validated Bootstrap contact form for your website!

Join My Telegram Channel to Download the Projects Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Code by: Jay

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our Bootstrap contact form.

After creating the files just paste the following below codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's go through the code step by step to understand its structure and functionality.

HTML Structure:

The code starts with the declaration of the HTML document type and the opening <html> tag. The lang attribute is set to "en" for English language.

Head Section:

Inside the <head> tags, the following elements are defined:

  • The title of the page is set to "Bootstrap 3 Contact form with Validation".
  • The character encoding is specified as UTF-8.
  • The viewport meta tag is used to ensure proper rendering on different devices.
  • Several CSS files are included using <link> tags. These files are hosted externally and provide styling for the form using Bootstrap and Bootstrap Validator.

Body Section:

The main content of the page is contained within the <body> tags.

Container:

A <div> element with the class "container" is created to hold the form.

Form:

Inside the container, a <form> element is defined with the following attributes:

  • class: "well form-horizontal" - This assigns the classes "well" and "form-horizontal" to the form for styling purposes.
  • action: " " - The form action is left empty, meaning it will be submitted to the same page.
  • method: "post" - The form data will be sent using the HTTP POST method.
  • id: "contact_form" - The form is given an ID for identification and manipulation in JavaScript.

Fieldset and Legend:

Within the form, a <fieldset> element is used to group related form elements together. It helps in semantic organization and accessibility. The fieldset is given a <legend> with the text "Contact Us Today!".

Form Inputs:

The form contains several input fields for capturing user information, such as first name, last name, email, phone number, address, city, state, zip code, website, hosting status, and project description. Each input field consists of:

  • A <label> element providing a description for the input.
  • A <div> with classes for layout purposes.
  • An <input> element to receive user input. The name attribute is used to identify the input when the form is submitted. The placeholder attribute provides an example or hint for the expected input.

Radio Buttons:

For the "Do you have hosting?" question, radio buttons are used. Two radio buttons are created with different values ("yes" and "no"). The radio buttons are grouped together using the same name attribute, allowing the user to select only one option.

Textarea:

A <textarea> element is used to capture the project description. It provides a larger text input area for the user to enter multiple lines of text.

Success Message:

A <div> element with the ID "success_message" is included to display a success message after the form is submitted. This element has the class "alert alert-success" for styling purposes.

Submit Button:

A submit button is added with the text "Send" and a glyphicon. It is styled as a warning button using the "btn btn-warning" classes.

External Scripts:

At the end of the code, several JavaScript files are included using <script> tags. These files are hosted externally and provide additional functionality for form validation and interactivity. The "script.js" file is also included, which is likely a custom JavaScript file written for this specific form.

This is the basic structure of our Bootstrap contact form using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

The CSS code #success_message { display: none; } targets an HTML element with the ID "success_message" and sets its display property to "none".

This CSS rule is useful for scenarios where you want to hide a particular element by default and then make it visible dynamically using JavaScript or other means. In this case, the success message is hidden initially and can be shown later when the form submission is successful using JavaScript code that modifies the CSS property of the element.

#success_message{
 display: none;
} 

Step 3 (JavaScript Code):

Finally, we use the jQuery library and Bootstrap Validator plugin to validate a contact form on a web page.

Let's break down the code:

$(document).ready(function() { ... });: This is a jQuery function that ensures the code inside the function is executed when the document (HTML page) has finished loading.

$('#contact_form').bootstrapValidator({ ... });: It selects the element with the ID "contact_form" and initializes the BootstrapValidator plugin on it. This plugin provides form validation functionality.

Inside the plugin initialization, there are several configuration options specified:

  • feedbackIcons: It defines the icons to be used for different validation states (valid, invalid, validating).
  • fields: It defines the validation rules for each form field.

Each field in the form has its own set of validators specified:

  • stringLength: It specifies the minimum and/or maximum length for the field's value.
  • notEmpty: It ensures that the field is not left empty.
  • emailAddress: It checks that the value entered is a valid email address.
  • phone: It checks that the value entered is a valid phone number for the specified country (in this case, US).
  • zipCode: It checks that the value entered is a valid ZIP code for the specified country (US).
  • .on('success.form.bv', function(e) { ... });: It attaches an event handler to the form's submit event when it passes the validation. The handler function is executed when the form is successfully validated and submitted.

    Inside the event handler function:

  • $('#success_message').slideDown({ opacity: "show" }, "slow"): It selects the element with the ID "success_message" and performs a sliding animation to display a success message.
  • $('#contact_form').data('bootstrapValidator').resetForm();: It resets the form's validation state and messages.
  • e.preventDefault();: It prevents the default form submission behavior.
  • var $form = $(e.target);: It selects the form element that triggered the event.
  • var bv = $form.data('bootstrapValidator');: It retrieves the BootstrapValidator instance associated with the form.
  • $.post($form.attr('action'), $form.serialize(), function(result) { ... }, 'json');: It sends an Ajax POST request to the form's action URL with the serialized form data. The response from the server is logged to the console as a JSON object.
  • Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

    $(document).ready(function() {
      $('#contact_form').bootstrapValidator({
          // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
          feedbackIcons: {
              valid: 'glyphicon glyphicon-ok',
              invalid: 'glyphicon glyphicon-remove',
              validating: 'glyphicon glyphicon-refresh'
          },
          fields: {
              first_name: {
                  validators: {
                          stringLength: {
                          min: 2,
                      },
                          notEmpty: {
                          message: 'Please supply your first name'
                      }
                  }
              },
               last_name: {
                  validators: {
                       stringLength: {
                          min: 2,
                      },
                      notEmpty: {
                          message: 'Please supply your last name'
                      }
                  }
              },
              email: {
                  validators: {
                      notEmpty: {
                          message: 'Please supply your email address'
                      },
                      emailAddress: {
                          message: 'Please supply a valid email address'
                      }
                  }
              },
              phone: {
                  validators: {
                      notEmpty: {
                          message: 'Please supply your phone number'
                      },
                      phone: {
                          country: 'US',
                          message: 'Please supply a vaild phone number with area code'
                      }
                  }
              },
              address: {
                  validators: {
                       stringLength: {
                          min: 8,
                      },
                      notEmpty: {
                          message: 'Please supply your street address'
                      }
                  }
              },
              city: {
                  validators: {
                       stringLength: {
                          min: 4,
                      },
                      notEmpty: {
                          message: 'Please supply your city'
                      }
                  }
              },
              state: {
                  validators: {
                      notEmpty: {
                          message: 'Please select your state'
                      }
                  }
              },
              zip: {
                  validators: {
                      notEmpty: {
                          message: 'Please supply your zip code'
                      },
                      zipCode: {
                          country: 'US',
                          message: 'Please supply a vaild zip code'
                      }
                  }
              },
              comment: {
                  validators: {
                        stringLength: {
                          min: 10,
                          max: 200,
                          message:'Please enter at least 10 characters and no more than 200'
                      },
                      notEmpty: {
                          message: 'Please supply a description of your project'
                      }
                      }
                  }
              }
          })
          .on('success.form.bv', function(e) {
              $('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
                  $('#contact_form').data('bootstrapValidator').resetForm();
    
              // Prevent form submission
              e.preventDefault();
    
              // Get the form instance
              var $form = $(e.target);
    
              // Get the BootstrapValidator instance
              var bv = $form.data('bootstrapValidator');
    
              // Use Ajax to submit form data
              $.post($form.attr('action'), $form.serialize(), function(result) {
                  console.log(result);
              }, 'json');
          });
    });

    Final Output:

    how to create a bootstrap contact form with validation.gif

    Conclusion:

    In this tutorial, we have explored the process of creating a Bootstrap contact form with validation to enhance user experience and improve data accuracy. By following the step-by-step guide, you have learned how to leverage Bootstrap's features and simplify the development of a functional contact form.

    We began by setting up the HTML structure, including the necessary form and input field elements. By incorporating Bootstrap's grid system, you can achieve a responsive layout that adapts to different screen sizes. Adding Bootstrap classes and components further enhances the form's appearance, making it visually appealing and professional.

    To ensure data accuracy, we implemented form validation using Bootstrap's built-in validation classes. By adding the required attribute to mandatory fields and utilizing the is-invalid class for invalid inputs, we provided real-time feedback to users. Additionally, we included error messages using Bootstrap's validation feedback component, guiding users to correct any errors.

    Customization and styling options were explored to match the contact form's design to your website's branding. By modifying Bootstrap classes and utilizing CSS, you can adjust colors, fonts, and other visual elements to create a cohesive user experience.

    Testing and troubleshooting the form is essential to ensure its functionality. By submitting different inputs and verifying that the required fields are validated correctly, you can confirm that the form performs as intended. Additionally, checking for successful form submissions and proper data handling ensures that user inquiries or messages are delivered to the desired destination.

    By creating a Bootstrap contact form with validation, you have not only improved the user experience on your website but also increased data accuracy. Visitors will appreciate the guidance provided by form validation, reducing frustration and errors. Furthermore, accurate data submission enables you to effectively respond to inquiries and engage with your audience.

    Now that you have completed this tutorial, you can apply your newfound knowledge to implement Bootstrap contact forms with validation in various web development projects. Remember to customize the form to align with your specific requirements and consistently test for optimal functionality.

    Create seamless and validated contact forms with Bootstrap, and enhance the user experience on your website today!

    That’s a wrap!

    I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

    Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

    And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

    Thanks!
    Faraz 😊

    End of the article

    Subscribe to my Newsletter

    Get the latest posts delivered right to your inbox


    Latest Post

    Please allow ads on our site🥺