typestar

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

  1. new FormData(form) collects every named control.
  2. checkValidity runs the browser's own rules.
  3. setCustomValidity adds one of your own.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 2 in Forms & storage, step 7 of 13 in The browser.

← Previous Next →