JavaScript form validation checks user input in the browser before a form is processed. It can give immediate feedback, prevent an incomplete submission, and apply rules that go beyond basic HTML constraints.
<form id="profileForm">
<input id="name" name="name" required>
<button type="submit">Submit</button>
</form>
const form = document.getElementById("profileForm");
form.addEventListener("submit", (event) => {
const name = document.getElementById("name").value.trim();
if (name === "") {
event.preventDefault();
}
});
For simple requirements, prefer native HTML attributes such as required, type, min, max and pattern. Use JavaScript when the rule depends on multiple controls or needs custom feedback. Client-side validation is useful for user experience, but it does not replace server-side validation. See the existing PHP form validation tutorial.
The browser can already enforce many common rules. This keeps JavaScript smaller and preserves useful accessibility behavior.
<input type="text" name="username" required minlength="3" maxlength="30">
<input type="email" name="email" required>
<input type="number" name="age" min="18" max="120">
Use the form’s submit event, test the rule, and call preventDefault() only when the submission should be stopped. For a custom validity message on a form control, setCustomValidity() integrates with the browser’s validation UI.
const form = document.getElementById("accountForm");
const password = document.getElementById("password");
const confirmPassword = document.getElementById("confirmPassword");
form.addEventListener("submit", (event) => {
confirmPassword.setCustomValidity("");
if (password.value !== confirmPassword.value) {
confirmPassword.setCustomValidity("Passwords must match.");
event.preventDefault();
confirmPassword.reportValidity();
}
});
Anything running in the browser can be bypassed or altered, so important data must be validated again on the server. JavaScript validation improves the interaction; server-side validation protects the application and data.
The older tutorial also linked to JavaScript enablement guidance, AJAX form validation, and AJAX form validation II; those links are preserved for readers working through the wider site.
Submit button · Reset button · Manage form elements with getElementById() · Listbox · JavaScript basics
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.