Creating a JavaScript Responsive Contact Form Validation a Step-by-Step Guide

In this tutorial, we will walk through the process of building a responsive contact form with validation using JavaScript. A responsive contact form ensures a seamless user experience across various devices, while validation helps ensure that users submit accurate and complete information.

Prerequisites

Make sure you have basic knowledge of HTML and CSS before starting. This tutorial assumes you have a basic understanding of these technologies.

Step 1: Set Up the HTML Structure

Create the HTML structure for the contact form. Include input fields for name, email, message, and a submit button.




  
  
  
  Contact Form



  

Step 2: Style the Form

Create a CSS file (styles.css) to style the form and make it responsive.

body {
  font-family: 'Arial', sans-serif;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f4f4f4;
}

.contact-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

form {
  display: grid;
  gap: 10px;
}

label {
  font-weight: bold;
}

input,
textarea {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}

button {
  background-color: #4caf50;
  color: #fff;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

Step 3: Implement JavaScript Validation

Create a JavaScript file (script.js) to handle form validation.

document.addEventListener('DOMContentLoaded', function () {
  const form = document.getElementById('contactForm');

  form.addEventListener('submit', function (event) {
    event.preventDefault();
    if (validateForm()) {
      // Form is valid, submit the data or perform other actions
      alert('Form submitted successfully!');
    }
  });

  function validateForm() {
    const name = document.getElementById('name').value;
    const email = document.getElementById('email').value;
    const message = document.getElementById('message').value;

    if (!name || !email || !message) {
      alert('Please fill in all fields.');
      return false;
    }

    if (!validateEmail(email)) {
      alert('Please enter a valid email address.');
      return false;
    }

    return true;
  }

  function validateEmail(email) {
    // Regular expression for basic email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  }
});

Step 4: Test and Finalize

Open the HTML file in a web browser and test your responsive contact form with validation. Make sure to fill in all fields, enter a valid email address, and observe the error messages when validation fails.

Related Posts