DOM Forms
Forms have specialised DOM APIs. Submit handlers, FormData, and the Constraint Validation API cover most of what you need.
Reading values
JS
const form = document.querySelector("#signup");
form.addEventListener("submit", (e) => {
e.preventDefault(); // stop the browser submitting
// Quickest read: FormData
const data = Object.fromEntries(new FormData(form));
console.log(data); // { email: "...", password: "..." }
// Individual field
form.email.value; // by name attribute
form.elements.email.value; // same — works in old browsers too
});
Validation API
JS
// Built-in checks
form.checkValidity(); // boolean
form.reportValidity(); // shows the browser tooltip
// Field-level
input.validity.valueMissing; // required not filled?
input.validity.typeMismatch; // wrong type (email, url)
input.validity.patternMismatch;
input.setCustomValidity("Names must be at least 2 chars");
input.setCustomValidity(""); // clear
Submitting via fetch (modern pattern)
JS
form.addEventListener("submit", async (e) => {
e.preventDefault();
if (!form.checkValidity()) { form.reportValidity(); return; }
const res = await fetch(form.action, {
method: form.method || "POST",
body: new FormData(form),
});
const json = await res.json();
// ... show success / error
});
| Helpful selectors | Matches |
|---|---|
input:required | Required fields. |
input:invalid | Live invalid state. |
input:placeholder-shown | Field is empty (showing placeholder). |
Tip: Set the HTML attributes (
required, type="email", pattern) and let the browser handle 90% of validation. Reach for JavaScript only for cross-field rules.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from DOM Forms!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Stop the form from navigating natively when it submits.
form.addEventListener('submit', (e) => { e.
(); /* handle */ });
A method on the event object.
Discussion
Loading…