JavaScript Form Validation

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.

Open simple text-validation demo
Table of Contents

Start with Native HTML Validation Top ↑

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">

Add Custom JavaScript Validation When Needed Top ↑

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();
  }
});

Validation by Form-Control Type Top ↑

Client-Side and Server-Side Validation Top ↑

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




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer