Skip to content
Browser & DOMChapter 40 / 47Intermediate4 min read

Forms & Validation

Learn modern JavaScript form validation with the submit event, FormData, required and pattern attributes, the Constraint Validation API and custom messages.

On this page

1. What are forms and validation?

A form is how you collect data from the user: login, signup, checkout, contact. JavaScript listens to the submit event, reads the values with FormData and checks them.

Validation happens in two places. Client side (in the browser) gives the user instant feedback. Server side is the real security, because anyone can bypass the browser check.

2. Why does it matter?

Without validation, wrong emails, empty fields and weak passwords reach the server. The user also finds out only after everything has already failed.

Without validationWith validation
An empty form reaches the serverThe error shows before submitting
The user does not know what is wrongA clear message next to each field
Useless requests hit the serverOnly valid data is sent
Read every value by handAll values at once with FormData

3. Where is it used?

FormValidation
SignupEmail format, password length, password match
CheckoutPhone number, address, required fields
ContactThe message must not be empty, length limit
SearchMinimum characters
ProfileAge range, file size and type

4. How does it work?

From submit to server
The user presses submit
The browser runs its built-in checks
preventDefault on the submit event
Read the values with FormData
Run custom checks and show a message if something is wrong
Everything is valid, so send it to the server with fetch
Built-in toolJob
required, minlength, pattern, type="email"Basic rules through HTML attributes
input.validityWhich rule failed, such as valueMissing
input.setCustomValidity(msg)Set your own error message
form.checkValidity()Is the whole form valid or not
form.reportValidity()Check and also show the browser's message

5. Code example

HTML:

html
<form id="signup" novalidate>
  <input name="email" type="email" required />
  <input name="password" type="password" minlength="8" required />
  <input name="confirm" type="password" required />
  <p id="error" role="alert"></p>
  <button>Signup</button>
</form>

JavaScript:

js
const form = document.querySelector("#signup");
const errorBox = document.querySelector("#error");

form.addEventListener("submit", async (event) => {
  event.preventDefault();

  const data = Object.fromEntries(new FormData(form));
  form.elements.confirm.setCustomValidity(
    data.password === data.confirm ? "" : "Passwords do not match"
  );

  if (!form.checkValidity()) {
    const firstInvalid = form.querySelector(":invalid");
    errorBox.textContent = firstInvalid.validationMessage;
    firstInvalid.focus();
    return;
  }

  errorBox.textContent = "";
  const res = await fetch("/api/signup", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email: data.email, password: data.password }),
  });
  errorBox.textContent = res.ok ? "Account created" : "Signup failed";
});

How does the code work?

LineWhat happens
novalidateTurns off the browser's default popups, so we show the messages ourselves
event.preventDefault()The page does not reload
new FormData(form)The value of every input that has a name
Object.fromEntries(...)Turned the FormData into a simple object
setCustomValidity(...)An empty string means valid, anything else is an error
:invalid and validationMessageThe first invalid field and its message

6. Common mistakes

Mistake: Trusting client side validation alone

Why? Anyone can bypass browser checks with DevTools or a direct API request.

Better: Use client side validation for UX, and check the same rules again on the server.

Mistake: Validating on the button click event

Why? When the form is submitted with the Enter key, the click handler never runs.

Better: Always attach the listener to the form's submit event.

Mistake: Not resetting setCustomValidity

Why? Once a message is set, the field stays invalid forever, even after the user fixes it.

Better: Call setCustomValidity('') when the value becomes valid.

Mistake: Forgetting the name attribute on inputs

Why? FormData only picks up fields that have a name, so values go missing.

Better: Give every input a unique name.

7. What to learn before and after

Suggested order
DOM Events
Forms and Validation
Submit with the Fetch API
Save drafts in Web Storage

Final quick revision

PointDetail
submit eventThe real form event, not click
preventDefault()Stop the reload and send with JavaScript
FormDataValues of fields that have a name
HTML rulesrequired, minlength, pattern, type
Custom rulessetCustomValidity, checkValidity
SecurityAlways validate on the server