iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Web Forms API

The Web Forms API covers everything browsers built into <form>: FormData for serialisation, Constraint Validation for built-in rules, and the new FormDataEvent for hooking submit behaviour.

FormData — read the form in one line

JS
const data = new FormData(form);

// Read fields
data.get("email");
data.getAll("tags");                       // multi-select returns array
[...data.entries()];                       // [["email","…"], ["pwd","…"]]

// Plain object — JSON-friendly
const obj = Object.fromEntries(data);

// Modify
data.set("ref", "header");
data.append("tags", "ops");
data.delete("password");

Send a form to a server

JS
// multipart/form-data (default, handles file uploads)
await fetch("/api/users", { method: "POST", body: new FormData(form) });

// JSON instead
await fetch("/api/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(Object.fromEntries(new FormData(form))),
});

Constraint Validation

Method / propertyReturns
form.checkValidity() / input.checkValidity()Boolean.
form.reportValidity()Same plus show browser tooltips.
input.validityObject of flags: valueMissing, typeMismatch, patternMismatch, …
input.setCustomValidity("msg")Mark invalid with a custom message.

HTML attributes you can rely on

HTML
<input type="email" required minlength="3" pattern="[a-z0-9._-]+@…">
<input type="number" min="0" max="100" step="0.5">
<input autocomplete="email" inputmode="email">
Tip: Set the right type and autocomplete attributes — phones swap to a tailored keyboard and password managers cooperate. Free UX wins.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from Web Forms API!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Turn a form into a plain object in one line.

const data = Object. (new FormData(form));

Test yourself

Q1. Read every field of a form quickly with…
Q2. Trigger native validation tooltips with…
Q3. For file uploads with FormData, you should…

Discussion

Loading…