Course: JavaScript Beginner
Lesson 17: Basic Form Validation
Level
Beginner
Estimated Reading Time
10–15 minutes
Goal
By the end of this lesson, the learner will be able to:
- Validate form inputs in JavaScript before allowing submission
- Display clear error messages next to invalid fields
- Reset validation state when the user corrects their input
Frontend Development Context
Form validation is one of the most user-facing responsibilities in frontend development. Without validation, users can submit empty forms, enter nonsense email addresses, set passwords shorter than any server would accept, or skip required fields — and only find out something was wrong after the server rejects the request. Client-side validation catches these problems instantly and gives the user clear, immediate feedback so they can fix the issue right away.
Good validation is not just about blocking bad input — it is about communicating clearly what went wrong and how to fix it. Error messages that say "Invalid input" are not helpful. Messages like "Email must contain an @ symbol" or "Password must be at least 8 characters" actually guide the user. Validation code that handles these messages well is a mark of a thoughtful frontend developer.
Explanation
The basic approach to JavaScript form validation is to intercept the form's submit event with event.preventDefault(), read each input's value, check it against your rules, and either show error messages (and stop) or proceed with submission if everything is valid.
A validation function for a field typically takes the value as input and returns either an error message string (if the value is invalid) or an empty string or null (if it is valid). This makes the function reusable and testable.
Showing errors typically involves selecting a dedicated error element near the input, setting its textContent to the error message, and adding an error CSS class to the input to highlight it in red. Clearing errors works the same way in reverse — empty the error text and remove the error class.
Common validation rules at the beginner level:
- Required:
value.trim().length === 0means the field is empty - Minimum length:
value.length < 8for passwords - Email format:
value.includes("@") && value.includes(".")is a simple but useful check - Number range:
Number(value) >= 1 && Number(value) <= 100
For more complex format validation, regular expressions (regex) are the tool to reach for — but simple string methods cover most beginner cases without the added complexity.
Code Example
This example validates a registration form with username, email, and password fields:
const form = document.querySelector("#register-form");
function showError(inputId, message) {
const input = document.querySelector(`#${inputId}`);
const error = document.querySelector(`#${inputId}-error`);
input.classList.add("input-error");
error.textContent = message;
}
function clearError(inputId) {
const input = document.querySelector(`#${inputId}`);
const error = document.querySelector(`#${inputId}-error`);
input.classList.remove("input-error");
error.textContent = "";
}
form.addEventListener("submit", function (event) {
event.preventDefault();
let isValid = true;
const username = document.querySelector("#username").value.trim();
const email = document.querySelector("#email").value.trim();
const password = document.querySelector("#password").value;
clearError("username");
clearError("email");
clearError("password");
if (username.length < 3) {
showError("username", "Username must be at least 3 characters.");
isValid = false;
}
if (!email.includes("@") || !email.includes(".")) {
showError("email", "Please enter a valid email address.");
isValid = false;
}
if (password.length < 8) {
showError("password", "Password must be at least 8 characters.");
isValid = false;
}
if (isValid) {
console.log("Form is valid — proceed with submission");
}
});
Code Explanation
The showError and clearError helper functions are responsible for all UI feedback. They take an input ID, find the corresponding input and error element, and either apply or remove the error class and message. Extracting this into functions means the submit handler stays clean and readable.
The submit handler clears all errors first — this ensures that if the user fixed a previous error, the message disappears before re-validating. This "clear then validate" pattern prevents stale error messages from lingering.
Each field is validated independently with a specific, descriptive message. The isValid flag starts as true and is set to false whenever a validation check fails. This allows all three errors to be shown at once (rather than stopping after the first failure), which is a much better user experience.
The final if (isValid) block only runs if no errors were found. In a real application, this is where you would call a function to send the data to a server. The pattern is clear: validate everything first, show all errors, then act only if everything passed.
Pattern Highlights
✅ Positive Pattern: Clear all error states at the start of validation before re-validating. This ensures that corrected inputs show as valid and prevents stale error messages from confusing the user.
⚠️ Neutral Note: Client-side validation improves user experience but is not a security measure. Always validate again on the server — JavaScript can be bypassed by anyone with browser DevTools.
❌ Negative Pattern: Stopping validation after the first failed field and showing only one error at a time forces users to submit the form multiple times to discover all their mistakes. Validate all fields and show all errors at once.
Common Mistakes
Mistake 1: Forgetting to clear errors before revalidating
If you show an error but never clear it, the error persists even after the user fixes the field — until they submit the form again and validation reruns.
form.addEventListener("submit", function (event) {
event.preventDefault();
// Without clearing first:
if (username.length < 3) {
showError("username", "Too short."); // shows but is never removed
}
// If user fixed username and resubmits — error still shows until this block runs again
});
Always clear all error states before running validation so the UI reflects the current state of the inputs.
Mistake 2: Using alert() for validation error messages
Showing errors with alert() is disruptive, blocks the UI, and provides a poor user experience.
if (email === "") {
alert("Email is required"); // blocks everything, not dismissible gracefully
}
Display error messages in the page near the relevant field — use a <span> or <p> with an ID that corresponds to the input. It is faster, less intrusive, and gives users context about which field has the problem.
Mistake 3: Trusting that trimmed values are validated
Trimming input removes whitespace, but does not validate the remaining content. A value of just spaces trimmed to "" should fail the required check, but code that only checks value.length > 0 before trimming would miss it.
const username = document.querySelector("#username").value; // " " (only spaces)
if (username.length > 0) {
// passes — but the trimmed value is empty!
}
// Correct: trim first, then validate
if (username.trim().length === 0) {
showError("username", "Username is required.");
}
Always .trim() the value before running validation rules, so whitespace-only inputs fail the required check.
Quick Recap
- Validate inputs in the form's
submithandler after callingevent.preventDefault()to stop the page reload - Show specific, helpful error messages next to the relevant field, not generic alerts
- Clear all error states before revalidating so stale messages do not persist after the user fixes an input
- Set a
isValidflag and check all fields before submitting — this shows all errors at once rather than one at a time