Forms

These programs are page scripts: they run in a browser page whose markup holds the fields they read, and the lines under each one are what its console prints. A command-line Node program has no document, so the same file started there stops with ReferenceError: document is not defined.

Read inputs

Form fields arrive as generic elements, so ask for the concrete kind. querySelector with HTMLInputElement unlocks value, and a null check guarantees the field exists before reading. The page holds one field with a padded name:

<input id="name" value=" Ada ">

const nameInput = document.querySelector<HTMLInputElement>("#name"); if (nameInput === null) { throw new Error("missing #name"); } const name: string = nameInput.value.trim(); console.log(name);

Ada

value is always a string, even for numbers, so convert with Number when math is needed. trim drops accidental spaces before validation ever sees the text. The program reads a field holding two spaces around Ada and prints the trimmed name.

Validate on submit

Check the values in one function that returns either an error message or nothing. Pure checks like length tests stay easy to unit test without any page at all: the program prints the result for an empty name, a one-letter name and a valid one.

function checkName(name: string): string | null { if (name.length === 0) { return "Name is required"; } if (name.length < 2) { return "Name is too short"; } return null; } console.log(checkName("")); console.log(checkName("A")); console.log(checkName("Ada"));

Name is required
Name is too short
null

null means valid, a string means broken. That tiny protocol keeps the submit handler below to one branch.

Show errors

Errors belong next to the field they describe. Write the message into a small hint element and highlight the input with a class. Clear both when the value turns valid, so old complaints never linger. The page holds the field and its hint:

<input id="name"> <span id="name-error"></span>

function showError(input: HTMLInputElement, message: string | null): void { const hint = document.querySelector("#name-error"); if (hint !== null) { hint.textContent = message ?? ""; } input.classList.toggle("invalid", message !== null); } const input = document.querySelector<HTMLInputElement>("#name"); if (input === null) { throw new Error("missing #name"); } showError(input, "Name is too short"); console.log(document.querySelector("#name-error")?.textContent, input.className);

Name is too short invalid

The double question marks fall back to an empty string, which clears the hint. toggle with a second argument adds the class exactly when a message exists. The program shows an error and prints the hint and the class of the field.

preventDefault

The submit event fires before the browser sends the form. Building on the helpers above, listen on the form, stop the default send with preventDefault when validation fails, and let valid data through untouched. The page holds the form, its field and its hint:

<form> <input id="name" value="A"> <span id="name-error"></span> </form>

function checkName(name: string): string | null { if (name.length === 0) { return "Name is required"; } if (name.length < 2) { return "Name is too short"; } return null; } function showError(input: HTMLInputElement, message: string | null): void { const hint = document.querySelector("#name-error"); if (hint !== null) { hint.textContent = message ?? ""; } input.classList.toggle("invalid", message !== null); } const nameInput = document.querySelector<HTMLInputElement>("#name"); if (nameInput === null) { throw new Error("missing #name"); } const form = document.querySelector<HTMLFormElement>("form"); if (form === null) { throw new Error("missing form"); } form.addEventListener("submit", (event) => { const problem = checkName(nameInput.value.trim()); showError(nameInput, problem); if (problem !== null) { event.preventDefault(); } }); const submit = new Event("submit", { cancelable: true }); form.dispatchEvent(submit); console.log(submit.defaultPrevented, document.querySelector("#name-error")?.textContent);

true Name is too short

preventDefault cancels the page reload, so the user reads the hint and fixes the field in place. Valid submits skip the branch and travel to the server as usual. The program dispatches a submit with a one-letter name and prints the prevented flag and the hint.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What type does input.value have, whatever the field holds?

    Answer

    string in every case

    Every form field gives its value as text, so a number needs a conversion such as Number(value).

  2. Why trim the value before validation?

    Answer

    It removes accidental spaces around the text

    A name typed with a trailing space would fail a length or emptiness check that the reader cannot see.

  3. What does a validator that returns string | null mean?

    Answer

    null means valid, a string means the message to show

    The tiny protocol keeps the submit handler to one branch: show the message when there is one.

  4. What does preventDefault() on a submit event stop?

    Answer

    The browser sending the form and reloading the page

    The default action of a submit is the request and the page change, and preventing it keeps the reader on the page with the hint.

  5. What does the second argument of classList.toggle("invalid", problem !== null) do?

    Answer

    It adds the class when the condition is true and removes it otherwise

    The flag makes the toggle a set-or-clear, so a valid field loses the class that marked it.

  6. What does this program print? function checkName(name: string): string | null { if (name.length === 0) { return "Name is required"; } if (name.length < 2) { return "Name is too short"; } return null; } console.log(checkName("A"));

    Answer

    Name is too short

    One letter is not empty but shorter than two, so the second branch returns its message.

  7. What does this program print? function checkName(name: string): string | null { if (name.length === 0) { return "Name is required"; } if (name.length < 2) { return "Name is too short"; } return null; } console.log(" Ada ".trim().length);

    Answer

    3

    trim drops the four spaces around Ada, and the three letters that remain are the length.

  8. What does this program print? const name = " Ada ".trim(); console.log(name === "Ada", name.length);

    Answer

    true 3

    The trimmed value equals Ada and holds three characters.

  9. What does the compiler say about this program? const input = document.querySelector<HTMLInputElement>("#name")!; const n: number = input.value; console.log(n);

    Answer

    error TS2322: Type 'string' is not assignable to type 'number'.

    The value of a field is text, so the compiler refuses to store it in a number without a conversion.

  10. What does the compiler say about this program? const input = document.querySelector<HTMLInputElement>("#name"); console.log(input.value.trim());

    Answer

    error TS18047: 'input' is possibly 'null'.

    The lookup may find nothing, and the compiler refuses to read a field of a value that may be null.

Article author: Arthur Isaev