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 validation | With validation |
|---|---|
| An empty form reaches the server | The error shows before submitting |
| The user does not know what is wrong | A clear message next to each field |
| Useless requests hit the server | Only valid data is sent |
| Read every value by hand | All values at once with FormData |
3. Where is it used?
| Form | Validation |
|---|---|
| Signup | Email format, password length, password match |
| Checkout | Phone number, address, required fields |
| Contact | The message must not be empty, length limit |
| Search | Minimum characters |
| Profile | Age range, file size and type |
4. How does it work?
| Built-in tool | Job |
|---|---|
required, minlength, pattern, type="email" | Basic rules through HTML attributes |
input.validity | Which 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:
<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:
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?
| Line | What happens |
|---|---|
novalidate | Turns 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 validationMessage | The 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
| Stage | Topics |
|---|---|
| Before | DOM Events, Event Bubbling & Delegation, Fetch API |
| Alongside | Regular Expressions, Error Handling |
| After | localStorage, sessionStorage & Cookies, Debounce & Throttle |
Final quick revision
| Point | Detail |
|---|---|
submit event | The real form event, not click |
preventDefault() | Stop the reload and send with JavaScript |
FormData | Values of fields that have a name |
| HTML rules | required, minlength, pattern, type |
| Custom rules | setCustomValidity, checkValidity |
| Security | Always validate on the server |