Form validation means checking that the data a user submits is actually usable before your code (or a server) tries to process it — a required field isn't empty, an email looks like an email, a password meets a minimum length. HTML provides some basic validation out of the box, but JavaScript gives you full control: custom rules, custom error messages, and the ability to validate as the user types, not just on submit.
Listening for the Submit Event
<!-- HTML -->
<form id="signup-form">
<input id="email" type="text" />
<p id="error" style="color: red;"></p>
<button type="submit">Sign Up</button>
</form>
const form = document.getElementById("signup-form");
const emailInput = document.getElementById("email");
const errorMsg = document.getElementById("error");
form.addEventListener("submit", function (event) {
event.preventDefault(); // stop the form from submitting/reloading the page
errorMsg.textContent = "";
if (emailInput.value.trim() === "") {
errorMsg.textContent = "Email is required.";
return;
}
console.log("Form is valid — submitting:", emailInput.value);
});
event.preventDefault() is essential here — without it, the browser's default behavior is to submit the form and reload the page immediately, which would wipe out any validation you just ran.
Checking Multiple Fields with a Basic Email Pattern
function isValidEmail(value) {
// A simple, practical check — not a perfect RFC-compliant regex
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}
form.addEventListener("submit", function (event) {
event.preventDefault();
const email = emailInput.value.trim();
if (email === "") {
errorMsg.textContent = "Email is required.";
} else if (!isValidEmail(email)) {
errorMsg.textContent = "Please enter a valid email address.";
} else {
errorMsg.textContent = "";
console.log("Valid email:", email);
}
});
Checking required fields first, then format, keeps the error messages specific and genuinely helpful instead of a single generic "invalid form" message.
HTML's Built-in Validation vs JavaScript
Attributes like required, type="email", and minlength give you free basic validation with zero JavaScript, and they're worth using as a first line of defense. But they're limited to simple rules and their error messages can't be styled consistently across browsers — which is exactly why most real sign-up forms layer JavaScript validation (as shown above, using event listeners) on top of them, for custom rules and a consistent user experience.
Remember that client-side validation is purely a user-experience improvement — it should never be the only check. Any data that matters for security or business logic must also be validated again on the server, since client-side JavaScript can always be bypassed.
