Form validation is an essential part of any website that collects user input. In this tutorial, you’ll learn how to validate a contact form using vanilla JavaScript, without relying on third-party libraries.
By the end, you’ll know how to:
- Check if fields are empty
- Validate email format
- Show custom error messages
Let’s make your forms smarter and user-friendly!
👁️ Preview
🧱 Step 1: Create the Contact Form (HTML)
Let’s start by building a simple contact form with fields for name, email, and message.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Contact Form Validation</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form id="contactForm">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" />
<small class="error-message"></small>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" />
<small class="error-message"></small>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea id="message"></textarea>
<small class="error-message"></small>
</div>
<button type="submit">Send</button>
</form>
<script src="script.js"></script>
</body>
</html>
🎨 Step 2: Basic CSS for Styling (Optional but Recommended)
body {
font-family: Arial, sans-serif;
padding: 2rem;
}
form {
max-width: 500px;
margin: auto;
}
.form-group {
margin-bottom: 1.5rem;
}
input, textarea {
width: 100%;
padding: 0.75rem;
border: 1px solid #ccc;
border-radius: 5px;
}
.error-message {
color: red;
font-size: 0.9rem;
display: none;
}
input.error, textarea.error {
border-color: red;
}
🧠 Step 3: Validate Form Fields with JavaScript
const form = document.getElementById("contactForm");
const nameInput = document.getElementById("name");
const emailInput = document.getElementById("email");
const messageInput = document.getElementById("message");
form.addEventListener("submit", function (e) {
e.preventDefault(); // Prevent form submission
let isValid = true;
clearErrors();
if (nameInput.value.trim() === "") {
showError(nameInput, "Name is required.");
isValid = false;
}
if (emailInput.value.trim() === "") {
showError(emailInput, "Email is required.");
isValid = false;
} else if (!isValidEmail(emailInput.value)) {
showError(emailInput, "Please enter a valid email address.");
isValid = false;
}
if (messageInput.value.trim() === "") {
showError(messageInput, "Message cannot be empty.");
isValid = false;
}
if (isValid) {
alert("Form submitted successfully!");
form.reset();
}
});
function showError(input, message) {
const formGroup = input.parentElement;
const errorMessage = formGroup.querySelector(".error-message");
errorMessage.innerText = message;
errorMessage.style.display = "block";
input.classList.add("error");
}
function clearErrors() {
const errorMessages = document.querySelectorAll(".error-message");
errorMessages.forEach((msg) => (msg.style.display = "none"));
const inputs = document.querySelectorAll("input, textarea");
inputs.forEach((input) => input.classList.remove("error"));
}
function isValidEmail(email) {
// Simple email regex
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
💡 Why Validate with JavaScript?
- Prevents incomplete or incorrect form submissions
- Gives users instant feedback
- Improves data quality and user experience
Even if you validate on the backend (which you should), client-side validation adds a smooth and friendly touch.
✅ Final Result
Now your contact form checks for:
- Empty fields
- Invalid email formats
- And gives custom error messages
All in real-time, with clean and readable JavaScript.