Author: admin
Client-Side Validated Contact Form Using HTML and JavaScript
This code implements a simple HTML contact form and includes JavaScript-based client-side validation with fully commented lines explaining each step. The HTML structure defines labeled input fields for name, email, subject, and message, along with hidden inline error messages that appear only when validation fails. The form intentionally disables the browser’s default validation using novalidate, allowing custom JavaScript logic to run instead. In the JavaScript section, the script retrieves references to all form fields and their corresponding error display elements, defines a lightweight email-format check, and provides helper functions to toggle error visibility. The main validation function trims and checks each field for minimum length or proper formatting, dynamically showing or hiding errors. When the form is submitted, the script prevents the default submission, validates all fields, displays a success message if everything passes, and resets the form. This combination of HTML and JavaScript demonstrates clear input handling, user feedback, and form-validation workflow for a basic client-side contact form.
<!doctype html> <!-- Tells the browser this is an HTML5 document -->
<html lang="en"> <!-- Sets the language of the page to English -->
<head> <!-- Head section: contains metadata and the title -->
<meta charset="utf-8"> <!-- Sets character encoding to UTF-8 -->
<meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Makes the page responsive on mobile -->
<title>Simple Contact Form</title> <!-- The page title displayed in the browser tab -->
</head>
<body> <!-- The visible body content begins -->
<h2>Contact Us</h2> <!-- Heading for the page -->
<!-- Form element; novalidate disables browser’s default validation -->
<form id="contactForm" novalidate> <!-- The form container -->
<label for="name">Name</label> <!-- Label describing the input field -->
<input type="text" id="name" name="name" placeholder="Your full name"> <!-- Text input for the name -->
<div id="nameError" style="color:red; display:none;"> <!-- Error message, hidden until needed -->
Please enter your name (at least 2 characters).
</div>
<br><br> <!-- Line breaks for spacing -->
<label for="email">Email</label> <!-- Label for email field -->
<input type="email" id="email" name="email" placeholder="you@example.com"> <!-- Email input -->
<div id="emailError" style="color:red; display:none;"> <!-- Email error message -->
Please enter a valid email address.
</div>
<br><br>
<label for="subject">Subject</label> <!-- Label for subject -->
<input type="text" id="subject" name="subject" placeholder="Subject"> <!-- Subject input field -->
<div id="subjectError" style="color:red; display:none;"> <!-- Subject error message -->
Subject must be at least 4 characters.
</div>
<br><br>
<label for="message">Message</label> <!-- Label for message textarea -->
<textarea id="message" name="message" placeholder="Write your message here..."></textarea> <!-- Message box -->
<div id="messageError" style="color:red; display:none;"> <!-- Message error element -->
Message must be at least 10 characters.
</div>
<br><br>
<button type="submit">Send Message</button> <!-- Submit button -->
<div id="successMessage" style="color:green; display:none;"> <!-- Success text shown only on valid submission -->
Your message was sent successfully! (Demo only)
</div>
</form> <!-- End of form -->
<script> <!-- Begin JavaScript validation code -->
const form = document.getElementById('contactForm'); // Grab the form element
const nameInput = document.getElementById('name'); // Reference to name field
const emailInput = document.getElementById('email'); // Reference to email field
const subjectInput = document.getElementById('subject'); // Reference to subject field
const messageInput = document.getElementById('message'); // Reference to message textarea
const nameError = document.getElementById('nameError'); // Reference to name error box
const emailError = document.getElementById('emailError'); // Reference to email error box
const subjectError = document.getElementById('subjectError'); // Reference to subject error box
const messageError = document.getElementById('messageError'); // Reference to message error box
const successMessage = document.getElementById('successMessage'); // Reference for success feedback
// Basic email validation function (checks for @ and .)
function isValidEmail(email) { // Function definition
return email.includes('@') && email.includes('.') && email.indexOf('@') > 0; // Returns true if email looks valid
}
// Show or hide an error message
function showError(element, show) { // element = target error box, show = boolean
element.style.display = show ? 'block' : 'none'; // Toggles display accordingly
}
// Main validation routine
function validateForm() { // Runs when form is submitted
let valid = true; // Assume valid until a rule fails
const name = nameInput.value.trim(); // Get trimmed name value
const email = emailInput.value.trim(); // Get trimmed email
const subject = subjectInput.value.trim(); // Get trimmed subject
const message = messageInput.value.trim(); // Get trimmed message
if (name.length < 2) { // If name is too short
showError(nameError, true); // Show name error
valid = false; // Mark form invalid
} else showError(nameError, false); // Hide error
if (!isValidEmail(email)) { // If email format is bad
showError(emailError, true); // Show email error
valid = false; // Mark form invalid
} else showError(emailError, false); // Hide error
if (subject.length < 4) { // If subject too short
showError(subjectError, true); // Show subject error
valid = false;
} else showError(subjectError, false);
if (message.length < 10) { // If message too short
showError(messageError, true); // Show error
valid = false;
} else showError(messageError, false);
return valid; // Return true only if all fields pass
}
// Handle form submission
form.addEventListener('submit', function(event) { // Listener for clicking submit
event.preventDefault(); // Prevent actual form submission
successMessage.style.display = 'none'; // Hide success message each attempt
const valid = validateForm(); // Run validation checks
if (valid) { // If all fields passed
successMessage.style.display = 'block'; // Show success message
form.reset(); // Clear all fields
}
});
</script> <!-- End JavaScript block -->
</body>
</html>
JavaScript Variables Quiz