Written by: Geoffrey Callaghan

How to Add Form Validation to Your Tailwind CSS Contact Form

How To Add Form Validation To Your Tailwind Css Contact Form

Adding form validation to a Tailwind CSS contact form involves both client-side validation (using JavaScript) to provide immediate feedback to users, and optionally server-side validation for additional security. Here’s how to implement client-side validation for a Tailwind CSS contact form.

Step-by-Step Guide

1. Create the Contact Form

First, set up your HTML contact form styled with Tailwind CSS.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Contact Form</title>
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">

  <form id="contact-form" class="bg-white p-6 rounded shadow-md w-full max-w-lg">
    <h2 class="text-2xl font-bold mb-4">Contact Us</h2>
    
    <div class="mb-4">
      <label for="name" class="block text-gray-700">Name</label>
      <input type="text" id="name" name="name" class="w-full p-2 border border-gray-300 rounded mt-1" required>
      <p id="name-error" class="text-red-500 text-sm mt-1 hidden">Name is required.</p>
    </div>
    
    <div class="mb-4">
      <label for="email" class="block text-gray-700">Email</label>
      <input type="email" id="email" name="email" class="w-full p-2 border border-gray-300 rounded mt-1" required>
      <p id="email-error" class="text-red-500 text-sm mt-1 hidden">Please enter a valid email address.</p>
    </div>
    
    <div class="mb-4">
      <label for="message" class="block text-gray-700">Message</label>
      <textarea id="message" name="message" class="w-full p-2 border border-gray-300 rounded mt-1" required></textarea>
      <p id="message-error" class="text-red-500 text-sm mt-1 hidden">Message is required.</p>
    </div>
    
    <button type="submit" class="bg-blue-500 text-white p-2 rounded hover:bg-blue-600">Submit</button>
    <p id="form-success" class="text-green-500 text-sm mt-4 hidden">Your message has been sent successfully!</p>
    <p id="form-error" class="text-red-500 text-sm mt-4 hidden">There was an error sending your message. Please try again.</p>
  </form>

  <script>
    document.getElementById('contact-form').addEventListener('submit', function(event) {
      event.preventDefault();
      
      // Clear previous errors
      document.querySelectorAll('.text-red-500').forEach(el => el.classList.add('hidden'));
      document.getElementById('form-success').classList.add('hidden');
      document.getElementById('form-error').classList.add('hidden');

      // Get form values
      const name = document.getElementById('name').value.trim();
      const email = document.getElementById('email').value.trim();
      const message = document.getElementById('message').value.trim();
      
      // Validate form values
      let hasError = false;
      
      if (!name) {
        document.getElementById('name-error').classList.remove('hidden');
        hasError = true;
      }
      
      const emailPattern = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
      if (!email || !emailPattern.test(email)) {
        document.getElementById('email-error').classList.remove('hidden');
        hasError = true;
      }
      
      if (!message) {
        document.getElementById('message-error').classList.remove('hidden');
        hasError = true;
      }
      
      if (hasError) return;

      // Simulate form submission
      setTimeout(() => {
        document.getElementById('form-success').classList.remove('hidden');
        event.target.reset();
      }, 1000);
    });
  </script>

</body>
</html>

Explanation

  1. HTML Form Setup: The form includes fields for name, email, and message, each with associated error messages initially hidden using the hidden class.

  2. Tailwind CSS: Tailwind classes style the form elements, ensuring a modern, responsive design.

  3. JavaScript Validation:

    • Event Listener: An event listener on the form’s submit event prevents the default form submission behavior.
    • Clear Previous Errors: Any previously displayed error messages or success messages are hidden at the beginning of each submission.
    • Validation Logic:
      • Name: Checks if the name field is empty.
      • Email: Validates the email format using a regular expression.
      • Message: Checks if the message field is empty.
    • Display Errors: If validation fails, corresponding error messages are displayed.
    • Simulate Submission: If validation passes, simulate a form submission by displaying a success message and resetting the form fields.

Customization Tips

  • Custom Error Messages: Adjust the error messages and validation logic according to your requirements.
  • Server-Side Validation: Enhance security by adding server-side validation in addition to client-side validation.
  • AJAX Submission: Replace the simulated form submission with an actual AJAX request to your server or serverless function for processing the form data.

This setup ensures your contact form is user-friendly and provides immediate feedback, enhancing the user experience.