How to Build a Contact Form with Javascript

Contact forms are an integral part of any website, providing visitors with a convenient way to connect with website owners. This article will guide you through the process of creating a contact form using HTML, CSS, and JavaScript. We’ll also explore the importance of accessibility and how to ensure that your form is accessible to all users.

Step 1: Crafting the HTML Form

The first step in building a contact form is to create the HTML form structure. You can achieve this by using the <form> element, which serves as a container for the form. Within the form element, you can add various form elements such as text inputs, text areas, checkboxes, and radio buttons. Here’s an example of a basic HTML form:

    <label for="name">Name</label>
    <input type="text" id="name" name="name">

    <label for="email">Email</label>
    <input type="email" id="email" name="email">

    <label for="message">Message</label>
    <textarea id="message" name="message"></textarea>

    <button type="submit">Submit</button>

In the above example, we’ve created a simple contact form with three form elements: a text input for the name, an email input for the email address, and a text area for the message. Additionally, a submit button has been included to allow visitors to send the form.

It’s important to note that each form element has a unique ID and name attribute. The ID attribute is used to identify the form element in CSS and JavaScript, while the name attribute is used when the form is submitted.

Step 2: Enhancing the Form with CSS Styling

Once the HTML form is in place, the next step is to style it using CSS. This can be easily accomplished by utilizing various CSS properties such as font-size, color, background-color, border, and padding. Here’s an example of some essential CSS to style the contact form:

form {
    width: 400px;
    margin: 0 auto;

input, textarea, button {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;

button {
    background-color: #007bff;
    color: #fff;
    border-radius: 5px;
    font-size: 16px;

button:hover {
    background-color: #0056b3;

In the above example, we’ve set the width of the form to 400px and centered it on the page using the margin property. Additionally, we’ve adjusted the font size and line height properties to improve text legibility.

See also  What Can I Do With Javascript

To ensure that the form elements occupy the full width of the form container, we’ve set their width to 100%. We’ve also added padding and a border to enhance the visual appeal of the form elements.

Finally, we’ve styled the submit button with a background color, padding, border radius, and font size. A hover effect has been added to change the background color when the mouse hovers over the button.

Step 3: Implementing JavaScript Validation

To validate the form and ensure that it is filled out correctly before submission, JavaScript validation can be employed. This helps prevent errors and enhances the user experience. JavaScript validation can be implemented using the onsubmit event handler, which triggers when the form is submitted. The onsubmit event handler can be utilized to verify that all required form fields are correctly completed. Here’s an example of basic JavaScript validation code:

function validateForm() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var message = document.getElementById("message").value;
    var error = "";

    if (name === "" || email === "" || message === "") {
        error = "Please fill in all required fields.";

    // Validate email format
    function validateEmail(email) {
        var re = /^[w-]+(.[w-]+)*@([w-]+.)+[a-zA-Z]{2,7}$/;
        return re.test(email);

    if (!validateEmail(email)) {
        error = "Please enter a valid email address.";

    if (error !== "") {
        return false;

    return true;

In the above example, we’ve created a validateForm() function that is called when the form is submitted. This function retrieves the values of the name, email, and message fields and checks that they are not empty. If any field is empty, an error message is assigned to the error variable.

The function also utilizes the validateEmail() function to ensure that the email address is formatted correctly using a regular expression. If any errors are detected, an alert message is displayed, and the function returns false, preventing the form from being submitted. If no errors are found, the function returns true, allowing the form to be submitted.

Step 4: Implementing Server-Side Validation

While JavaScript validation improves user experience, it is not sufficient to ensure accurate form completion. Server-side validation is necessary to prevent malicious attacks and validate form data processing. Server-side validation can be implemented using server-side scripting languages like PHP, Ruby, or Python. The server-side script allows you to validate form data and send an email to the website owner. Here’s an example of a basic PHP code to process form data:

$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$message = trim($_POST["message"]);

$name = strip_tags($name);
$email = strip_tags($email);
$message = strip_tags($message);

$email = filter_var($email, FILTER_SANITIZE_EMAIL);

if (empty($name) || empty($email) || empty($message)) {
    $error = "Please fill in all required fields.";
    echo $error;
} else {
    $recipient = "";
    $subject = "New Contact Form Submission";
    $email_content = "Name: " . $name . "n";
    $email_content .= "Email: " . $email . "n";
    $email_content .= "Message: " . $message . "n";

    $headers = "From: " . $name . " <" . $email . ">";

    if (mail($recipient, $subject, $email_content, $headers)) {
        echo "Thank you! Your message has been sent.";
    } else {
        echo "Oops! Something went wrong while sending the email.";

In the above example, we’ve utilized the PHP $_POST superglobal to retrieve the values of the name, email, and message fields. The trim() function is then used to remove any leading or trailing whitespace from the values, while the strip_tags() function is used to remove any HTML tags.

See also  Exit Intent Popup: A Guide to Creating an Engaging Modal

The filter_var() function is used to validate the email address and remove any unwanted characters. Subsequently, we check that all required fields have been correctly filled. If any errors are detected, we return a 400 Bad Request status code and an error message.

If no errors are found, we define variables for the recipient email address, subject, and email content. We also include the sender’s name and email address in the headers variable.

Finally, we use the PHP mail() function to send the email. If the email is sent successfully, we return a 200 OK status code and a success message. In the event of an email sending failure, we return a 500 Internal Server Error status code and an error message.

Step 5: Testing the Form

After completing the form, thorough testing is crucial to ensure its correct functionality. Here are some tests you can perform:

  • Test form validation by submitting the form with invalid or missing data. Verify that the validation error messages are displayed correctly.
  • Test form submission by submitting the form with valid data. Confirm that the email is sent successfully, and the correct success message is displayed.
  • Test form accessibility by utilizing a screen reader to navigate through the form. Ensure that it is easy to use and comprehend.

Step 6: Enhancing Accessibility

Accessibility should be a significant consideration when creating a contact form. Here are some tips for improving the accessibility of your form:

  • Use semantic HTML elements like <form>, <label>, and <input> to structure the form. This helps screen readers and other assistive technologies understand the form’s organization.
  • Associate labels with their corresponding form fields using the for attribute on <label> elements. This allows screen readers to announce the label when the form field is focused.
  • Utilize the title attribute to provide additional information about form fields. This is beneficial for users who cannot see the form or utilize a screen reader.
  • Include the required attribute on required form fields. This informs users who cannot visually see the form that a field is necessary before submitting.
  • Provide clear error messages when the form is submitted with invalid data. These messages should clarify the nature of the error and offer suggestions for correction.
See also  JavaScript Summer Camp: Your Ultimate Guide

Step 7: Optimizing for SEO

Optimizing your contact form for search engine optimization (SEO) is essential for driving traffic to your website. Here are some SEO tips for optimizing your form:

  • Use descriptive, keyword-rich text in the form field labels and the form itself. This can enhance the page’s relevance for the keywords you’re targeting.
  • Incorporate descriptive, keyword-rich text in the page title and meta description. This can boost the click-through rate from search engine results pages.
  • Implement markup to add structured data to your contact form. This helps search engines understand the form’s purpose and structure.
  • Ensure that the form is included in the site map and that the site map is submitted to search engines. This aids search engines in discovering and indexing the form more effectively.
  • Use alt text on any images used in the form. This improves the page’s relevance for targeted keywords and enhances form accessibility for users who cannot view images.

By following these steps, you can create a contact form that is user-friendly, accessible, and effective in capturing leads and facilitating communication with your website visitors. ProgramMatek provides additional resources and expertise in web development and contact form optimization.