Script Valley
Building Your Developer Portfolio
Adding Interactivity with JavaScriptLesson 3.4

How to build a working contact form with JavaScript validation

form validation, preventDefault, required field checks, email regex, error message display, form submission feedback, Formspree integration

Contact Form With Client-Side Validation

A contact form without validation sends empty or malformed data. Validate before submitting and give users immediate feedback when something is wrong.

HTML Form

<form id="contact-form">
  <input type="text" id="name" placeholder="Your name" />
  <input type="email" id="email" placeholder="your@email.com" />
  <textarea id="message" placeholder="Your message"></textarea>
  <button type="submit">Send Message</button>
  <p id="form-status"></p>
</form>

JavaScript Validation + Formspree

const form = document.querySelector('#contact-form');
const status = document.querySelector('#form-status');
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  const name = document.querySelector('#name').value.trim();
  const email = document.querySelector('#email').value.trim();
  const message = document.querySelector('#message').value.trim();

  if (!name || !email || !message) {
    status.textContent = 'All fields are required.';
    return;
  }
  if (!emailRegex.test(email)) {
    status.textContent = 'Enter a valid email address.';
    return;
  }

  const res = await fetch('https://formspree.io/f/YOUR_ID', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name, email, message })
  });

  status.textContent = res.ok ? 'Message sent!' : 'Something went wrong.';
});

Formspree is a free service that handles form submissions without a backend. Replace YOUR_ID with your Formspree endpoint ID after creating a free account. Always handle the res.ok check to inform users of failures.

Up next

How to add an active nav link highlight based on scroll position

Sign in to track progress