Forms in JavaScript
FormData reads the fields; the constraint API reports validity.
function submit(form) {
form.addEventListener("submit", (event) => {
event.preventDefault();
const data = new FormData(form);
const values = Object.fromEntries(data.entries());
const langs = data.getAll("langs");
const handle = form.elements.namedItem("handle");
handle.setCustomValidity(
values.handle?.length >= 3 ? "" : "at least three characters",
);
if (!form.checkValidity()) {
form.reportValidity();
return;
}
console.log({ ...values, langs });
});
}
How it works
new FormData(form)collects every named control.checkValidityruns the browser's own rules.setCustomValidityadds one of your own.
Keywords and builtins used here
Objectconstfunctionifreturn
The run, in numbers
- Lines
- 20
- Characters to type
- 460
- Tokens
- 122
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 73 seconds.
Step 1 of 2 in Forms & storage, step 7 of 13 in The browser.