JavaScript Foundations • StreetGeek Academy
🧠 MODULE 8: Forms & Validation
Learn how to validate and handle form input with JavaScript, provide real-time feedback, and enhance your portfolio’s contact form UX.
1) Why Form Validation Matters
Form validation ensures users enter correct information before submission.
It improves data quality, prevents errors, and enhances user experience.
Example
- ✅
user@example.com→ valid - ❌
userexample.com→ invalid
You’ll learn both built-in HTML validation and custom JS validation.
2) Example Contact Form (Base HTML)
Add this to your portfolio’s Contact page:
<form id="contactForm">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Your name" required>
<label for="email">Email</label>
<input type="email" id="email" placeholder="you@example.com" required>
<label for="message">Message</label>
<textarea id="message" rows="4" placeholder="Write your message..." required></textarea>
<button type="submit">Send Message</button>
<p id="form-status"></p>
</form>
required attributes for basic HTML5 validation.
3) Capturing and Handling Form Submission
Use JavaScript to stop page reload and process the form manually.
const form = document.getElementById("contactForm");
const status = document.getElementById("form-status");
form.addEventListener("submit", (e) => {
e.preventDefault(); // Prevent reload
status.textContent = "Submitting...";
});
4) Validating Inputs Manually
form.addEventListener("submit", (e) => {
e.preventDefault();
const name = document.getElementById("name").value.trim();
const email = document.getElementById("email").value.trim();
const message = document.getElementById("message").value.trim();
if (name === "" || email === "" || message === "") {
status.textContent = "⚠️ Please fill in all fields.";
status.style.color = "red";
return;
}
if (!email.includes("@") || !email.includes(".")) {
status.textContent = "⚠️ Please enter a valid email address.";
status.style.color = "red";
return;
}
status.textContent = "✅ Message sent successfully!";
status.style.color = "green";
form.reset();
});
5) Adding Live (Real-Time) Validation
Example: Live Email Check
const emailField = document.getElementById("email");
emailField.addEventListener("input", () => {
if (emailField.value.includes("@") && emailField.value.includes(".")) {
emailField.style.borderColor = "green";
} else {
emailField.style.borderColor = "red";
}
});
6) Using Regular Expressions (Regex) for Advanced Validation
Regex gives you fine control over patterns like emails, phone numbers, and passwords.
Example Email Regex
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
status.textContent = "❌ Invalid email format.";
}
Example Phone Regex
const phonePattern = /^\d{3}-\d{3}-\d{4}$/; // e.g., 555-123-4567
7) Displaying Inline Error Messages
Instead of one status line, show errors near the inputs.
HTML
<div class="field">
<label for="name">Name</label>
<input id="name" type="text">
<small class="error"></small>
</div>
JavaScript
function showError(input, message) {
const small = input.nextElementSibling;
small.textContent = message;
small.style.color = "red";
}
form.addEventListener("submit", (e) => {
e.preventDefault();
const name = document.getElementById("name");
const email = document.getElementById("email");
if (name.value.trim() === "") {
showError(name, "Name is required");
} else {
showError(name, "");
}
if (!email.value.includes("@")) {
showError(email, "Enter a valid email");
} else {
showError(email, "");
}
});
8) Preventing Spam (Basic Honeypot Technique)
Add a hidden field to trap bots:
<input type="text" id="website" style="display:none;">
const honeypot = document.getElementById("website");
if (honeypot.value !== "") {
return; // Stop spam bots
}
9) Optional Enhancement — Confirmation Modal
Use a small modal popup instead of text feedback:
if (formIsValid) {
alert("Thanks for reaching out! We'll reply soon.");
}
alert() with a styled modal or animation.
10) Quiz Time
Show/Hide Questions
1) What does e.preventDefault() do?
2) How do you access an input’s value in JavaScript?
3) What is the purpose of a Regular Expression (Regex)?
4) How can you provide real-time feedback while the user types?
5) What should happen after successful form submission?
🚀 Challenge Task — Smart Contact Form
Make your contact form fully interactive:
Requirements
- Prevent page reload
- Validate that all fields are filled
- Use regex to validate email
- Show inline errors next to each field
- Display a success message on valid submission
- Reset the form afterward
Bonus: Character Counter for Message Field
const message = document.getElementById("message");
const statusSmall = document.createElement("small");
message.parentElement.appendChild(statusSmall);
message.addEventListener("input", () => {
const remaining = 200 - message.value.length;
statusSmall.textContent = `${remaining} characters remaining`;
});
🏁 Module 8 Summary
- How to handle form submission with JavaScript
- How to validate user input and display helpful feedback
- How to use regex for pattern-based validation
- How to provide real-time feedback
- How to create a smooth, error-free contact experience
Next up → MODULE 9: Fetch API, Async/Await & Local Storage
We’ll connect your portfolio to real data — like fetching live GitHub projects or storing user preferences (dark mode, likes, etc.) directly in the browser.