Skip to content
HopperHopper

Course navigation

Phase 4 · The browserDay 20

Forms and validation

  • About 75 minutes
  • 8 sections
  • Runnable TypeScript examples
  • Practice questions

Before you start

About 75 minutes

By the end you will be able to

  1. Build a form with labels and inputs, handle its submit event, and stop the page from reloading with preventDefault.
  2. Read what the user typed with input.value or FormData, knowing that every form value arrives as a string.
  3. Turn form text into validated, typed data with a result union, and collect every problem in one pass.
  4. Show each error next to its field so that screen readers announce it, and explain what the browser's built-in validation can and cannot do.

What to remember from earlier

Section 1 of 8

20.1 Forms, Labels, and Inputs

Before you start, create a new Vite project named day20 exactly as you did on Day 18 (the vanilla TypeScript template), and start it with npm run dev. Delete the sample code Vite put in src/main.ts. Every page today comes in two files: a .html file with the page’s markup, and a .dom.ts file with its script. To try one, paste the markup into index.html in place of <div id="app"></div> (keep the <script> line below it), paste the script into src/main.ts, and look at the page in the browser. The few .ts files with no .dom in their names are ordinary Node programs: put those in a separate folder, set up as on Day 13, and run them with node.

So far your pages have listened to clicks and key presses. That is enough for a counter or a to-do list where every task is already written, but most real pages also need the user to type something: a name, an email address, an age, the price of lunch. Day 13’s programs could read text from process.argv, but a web page has no command line. It has forms.

A form is a part of a page that collects typed answers and sends them all together, like a paper form you fill in and then hand over. In HTML it is a <form> element, and inside it go the pieces you already know from every website you have used:

Element What it is
<input> A box the user types into. It has no closing tag.
<label> The visible name of an input, such as “Your name”
<button type="submit"> The button that sends the form

An input has a few attributes that matter all day:

  • type says what kind of value it holds: "text" for any text, "number" for a number, "email" for an email address. The browser uses it to pick a keyboard on a phone and, as 20.7 shows, to do some checking of its own.
  • id is the element’s unique name on the page, as on Day 18; your script finds it with querySelector("#name"), and a label points to it.
  • name is the field’s name inside the form. When the form’s answers are gathered up (20.3), each one is filed under its input’s name.

A label is tied to one input by its for attribute, which must equal that input’s id. The link does three things. A screen reader (a program that reads the page aloud for someone who cannot see it) says “Your name, edit text” when the user reaches the box, instead of just “edit text”. Clicking the label puts the cursor in the input, which gives everyone a bigger target. And anyone reading your markup can see which text belongs to which box.

Worked example: A one-field form

Here is the page you will use in 20.2. Read it from the top:

greet.html
<form id="greet-form">
  <label for="name">Your name</label>
  <input id="name" name="name" type="text">
  <button type="submit">Say hello</button>
</form>
<p id="greeting"></p>
Line What it does
1 Starts a form with the id greet-form, so the script can find it
2 A label whose for="name" points at the input with id="name"
3 The input: id="name" for the label and the script, name="name" for the form’s answers
4 A submit button; clicking it sends the form
5 Ends the form
6 An empty paragraph outside the form, where the script will write the greeting

The input’s id and name happen to be the same word here. They do not have to be, and they do different jobs: the id is for the label and querySelector; the name is for the form’s answers.

Now vary the markup. A label can also wrap its input, and then it needs no for:

<label>
  Your name
  <input id="name" name="name" type="text" />
</label>

Both forms link the label to the input. This course uses for and id, because the label and the input can then sit anywhere in the form, and because every screen reader handles that form the same way.

Notice what a form is not: it is not a box for an input to sit in so it looks tidy. The <form> element is what makes the button send the answers and what lets the Enter key do the same (20.2). An <input> outside any form still lets the user type, but nothing gets sent.

Watch out

A for that does not match the id. A label written <label for="username"> above <input id="name"> looks fine on the screen, and the browser gives no error. But the two are not linked: clicking the label does nothing, and a screen reader announces the box with no name at all. Make for equal to the input’s id exactly, including capital letters.

Key idea

A <form> groups inputs that are sent together. Each <input> has an id (for its label and your script) and a name (for the form’s answers), and each has a <label> whose for equals the input’s id.

Pause and try

Question 1 · Multiple choice

Which markup links the label to the input, so that clicking “Email” puts the cursor in the box?

  1. <label for="email-box">Email</label> <input id="email" name="email-box">
  2. <label for="email">Email</label> <input id="email" name="address">
  3. <label id="email">Email</label> <input for="email" name="email">
  4. <label name="email">Email</label> <input name="email">
Check your reasoning

B. A label’s for must equal the input’s id. In B both are "email"; the input’s name can be any word, because name is only for the form’s answers.

  • A is wrong: for matches the input’s name, not its id. The label is linked to nothing.
  • C is wrong: the attributes are on the wrong elements. A label has for, an input has id.
  • D is wrong: name does not link anything; the label has no for.

Reread 20.1 Forms, Labels, and Inputs if you chose differently.

Question 2 · Short answer

A designer wants to drop the labels and put grey hint text inside each box instead (“Your name”), which disappears as soon as the user starts typing. Give two problems with that plan.

Check your reasoning

A good answer names two of these:

  • A screen reader user is not told what each box is for; a label is what gives the input its name.
  • Once the user types, the hint disappears, so while checking their answers (or reading an error message) they can no longer see which box was which.
  • There is no label to click, so the target for putting the cursor in the box is smaller.

Labels are visible all the time and are linked to their inputs, so they solve all three. Reread 20.1 Forms, Labels, and Inputs if your answer differed.

Section 2 of 8

20.2 The submit Event and preventDefault

A form with no script still does something when you press its button: the browser sends it. That is how the web worked before scripts existed. The browser gathers the answers, adds them to the page’s address (?name=Ana), and loads that address as a brand-new page. A program on a web server would read the answers and send back a reply.

Your app has no server; the script is the program. And loading a new page is a disaster for a script: everything the page had (your variables, your rendered list, the greeting you just wrote) is thrown away, and the script starts again from line 1. So you need two things: a way to find out the user sent the form, and a way to tell the browser not to load a new page.

The first is an event, as on Day 19. When a form is sent, by clicking its submit button or by pressing Enter inside one of its inputs, the browser fires a submit event on the <form> element. You listen for it with addEventListener("submit", …) on the form, not on the button, so that one listener covers both ways of sending.

The second is a method of the event object. Many events come with a default action: something the browser does on its own after your listeners run. A link’s default action is to open its page; a form’s is to send itself and load a new page. Calling event.preventDefault() inside the listener cancels the default action, so the browser stays on the current page and your script keeps running.

Worked example: Greeting from a form

Here is the script for greet.html from 20.1:

greet.dom.ts
const form = document.querySelector<HTMLFormElement>("#greet-form");
const nameInput = document.querySelector<HTMLInputElement>("#name");
const greeting = document.querySelector<HTMLParagraphElement>("#greeting");
if (form === null || nameInput === null || greeting === null) {
  throw new Error("The page is missing the form, the input or the greeting");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  greeting.textContent = `Hello, ${nameInput.value}!`;
  console.log(`Submitted: ${nameInput.value}`);
});

The user types Ana and presses Enter, then types Ben and clicks Say hello. The paragraph ends up showing:

<p id="greeting">Hello, Ben!</p>

and the browser’s console (Day 18) shows:

Submitted: Ana
Submitted: Ben
Line What happens
1–3 Day 18’s querySelector with a type: HTMLFormElement is the element type for a <form>, as HTMLInputElement is for an input
4–6 Each can be null, so one check rules all three out; after it, the checker knows they are real elements
8 The listener is attached to the form, for the submit event; it runs once for each send
9 Cancels the default action: no new page loads
10 nameInput.value is the text in the box right now; the template literal builds the greeting
11 Logs the name, so you can count the sends in the console

The first send fires submit, line 10 writes “Hello, Ana!”, and the page stays. The second send fires submit again and replaces the text with “Hello, Ben!”. Two sends, two log lines, one page that never reloaded.

Hover over event on line 8 in VS Code: its type is SubmitEvent. You did not write that; the checker knows that "submit" events are SubmitEvents, just as Day 19’s "click" events are MouseEvents. preventDefault exists on every event type, because many events have a default action.

What does the user see without line 9? Here is the same listener with it removed:

form.addEventListener("submit", () => {
  greeting.textContent = `Hello, ${nameInput.value}!`;
});

The listener runs, and for a split second “Hello, Ana!” appears. Then the browser carries on with the default action: the address changes to end in ?name=Ana, the page reloads, the paragraph is empty again, and the console is cleared. Nothing is wrong as far as npx tsc or the browser are concerned. It just does not do what you wanted.

Watch out

Forgetting event.preventDefault(). The symptom is always the same: the page flashes, what your script wrote vanishes, the box empties, and ? plus the answers appears at the end of the address. No error is shown, because sending the form is exactly what a form is supposed to do. Make event.preventDefault() the first line of every submit listener.

Key idea

Listen for submit on the <form>, not click on the button, so Enter and the button both work. Call event.preventDefault() first, or the browser loads a new page and your script’s work disappears.

Pause and try

Question 3 · Multiple choice

A student’s form shows its result for a moment, then the result disappears and the address bar ends in ?city=Lima. What is the most likely cause?

  1. The input has no <label>.
  2. The submit listener does not call event.preventDefault().
  3. The script used textContent instead of innerHTML.
  4. npx tsc reported a type error, so the script did not run.
Check your reasoning

B. The answers in the address and the lost result are the default action of a submit: the browser sent the form and loaded a new page. event.preventDefault() cancels that.

  • A is wrong: a missing label hurts screen reader users, but it does not reload the page.
  • C is wrong: both set what an element shows; neither has anything to do with sending a form.
  • D is wrong: the result appeared for a moment, so the script did run. Also, npx tsc only reports; it does not stop Vite from running the page.

Reread 20.2 The submit Event and preventDefault if you chose differently.

Question 4 · Short answer

Explain why the greeting script attaches its listener to the form’s submit event rather than the button’s click event. Then say what nameInput.value holds at the moment line 10 runs.

Check your reasoning

submit is the event that means “the user sent this form”, however they did it: clicking the button or pressing Enter in the input both fire it. It is also the event whose default action (loading a new page) needs to be prevented. And as 20.7 shows, the browser fires it only after its own checks pass.

nameInput.value is the text in the box at that moment, as a string: "Ana" on the first send and "Ben" on the second. The value is read each time the listener runs, not once when the page loads.

Reread 20.2 The submit Event and preventDefault if your answer differed.

Section 3 of 8

20.3 Reading Values: input.value and FormData

The greeting only had to show what was typed. Most forms need to compute with it: add two numbers, compare an age with a limit. That raises a question Day 2 already answered for process.argv on Day 13: what type is the thing the user typed?

The answer is: always a string. An input’s value property is the text in the box, and its type is string, whatever the input’s type attribute says. type="number" gives a phone a number keyboard and makes some browsers refuse letters, but the value still arrives as text: "40", not 40. If the box holds something that is not a number, a number input’s value is the empty string "".

Watch out

Adding two values without converting them. Here is a form with two number inputs:

add-strings.html
<form id="add-form">
  <label for="first">First number</label>
  <input id="first" name="first" type="number">
  <label for="second">Second number</label>
  <input id="second" name="second" type="number">
  <button type="submit">Add</button>
</form>
<p id="total"></p>
add-strings.dom.ts
const form = document.querySelector<HTMLFormElement>("#add-form");
const first = document.querySelector<HTMLInputElement>("#first");
const second = document.querySelector<HTMLInputElement>("#second");
const total = document.querySelector<HTMLParagraphElement>("#total");
if (form === null || first === null || second === null || total === null) {
  throw new Error("The page is missing an element");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  total.textContent = `Total: ${first.value + second.value}`;
});

The user types 40 and 10 and clicks Add. The page shows:

<p id="total">Total: 4010</p>

npx tsc is happy, because first.value + second.value is string + string, which is allowed: it joins the strings, exactly like Day 3’s "5" + 1. The checker cannot know you meant arithmetic. Convert each value first with Day 2’s Number():

add-numbers.dom.ts
const form = document.querySelector<HTMLFormElement>("#add-form");
const first = document.querySelector<HTMLInputElement>("#first");
const second = document.querySelector<HTMLInputElement>("#second");
const total = document.querySelector<HTMLParagraphElement>("#total");
if (form === null || first === null || second === null || total === null) {
  throw new Error("The page is missing an element");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const sum = Number(first.value) + Number(second.value);
  total.textContent = `Total: ${sum}`;
});

With the same page and the same typing, the result is now right:

<p id="total">Total: 50</p>

input.value is fine when you have one or two inputs. With six, you would need six querySelector calls and six null checks. FormData reads the whole form at once. new FormData(form) makes a snapshot of every input in the form that has a name, and its get(name) method gives the value filed under that name.

What type does get return? Not string: it is FormDataEntryValue | null. FormDataEntryValue is itself a union, string | File: a form can also contain a file-upload input, whose answer is a File. And null means “no input in this form has that name”, which is what you get from a typo. So before using the value as a string, narrow it with Day 9’s typeof.

Worked example: Reading a form with FormData

book-form.html
<form id="book-form">
  <label for="title">Title</label>
  <input id="title" name="title" type="text">
  <label for="pages">Pages</label>
  <input id="pages" name="pages" type="number">
  <button type="submit">Save</button>
</form>
<p id="summary"></p>
book-form.dom.ts
const form = document.querySelector<HTMLFormElement>("#book-form");
const summary = document.querySelector<HTMLParagraphElement>("#summary");
if (form === null || summary === null) {
  throw new Error("The page is missing the form or the summary");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(form);
  const title = data.get("title");
  const pages = data.get("pages");
  console.log(typeof title, typeof pages);
  if (typeof title !== "string" || typeof pages !== "string") {
    return;
  }
  summary.textContent = `${title.trim()}: ${Number(pages) + 1} pages with the cover`;
});

The user types Dune (with spaces around it) as the title and 412 as the pages, then clicks Save. The console shows:

string string

and the page shows:

<p id="summary">Dune: 413 pages with the cover</p>
Line What happens
9 new FormData(form) reads every named input in the form as it is right now
10–11 get("title") and get("pages") look values up by each input’s name attribute; both have type FormDataEntryValue | null
12 At run time both are strings, even pages, which came from a number input
13–15 Narrows both: if either is not a string, stop. After this if, the checker knows both are string
16 trim() removes the spaces, and Number(pages) + 1 is arithmetic, 413, because pages was converted first

What happens if you skip the narrowing and use the value as a number? Here is the book form’s listener, written that way:

form-data-number.dom.ts
const form = document.querySelector<HTMLFormElement>("#book-form");
const summary = document.querySelector<HTMLParagraphElement>("#summary");
if (form === null || summary === null) {
  throw new Error("The page is missing the form or the summary");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(form);
  const pages: number = data.get("pages");
  summary.textContent = `${pages + 1} pages with the cover`;
});
form-data-number.dom.ts:10:9 - error TS2322: Type 'FormDataEntryValue | null' is not assignable to type 'number'.
  Type 'null' is not assignable to type 'number'.

The checker stops at line 10, the annotation pages: number. Its second line names one member that does not fit; string and File would not fit either. The fix is the two steps from the worked example: narrow to string, then convert with Number(). Put book-form.dom.ts back in src/main.ts before your next check.

You will narrow a FormData value to a string so often today that it is worth a small function. Every page from 20.6 on uses this one: it gives the text filed under name, or "" when there is no such text input.

function textOf(data: FormData, name: string): string {
  const value = data.get(name);
  return typeof value === "string" ? value : "";
}

Key idea

Every value a form gives you is a string: input.value is a string, and FormData’s get(name) is a FormDataEntryValue | null that you narrow to string. Convert with Number() before doing arithmetic.

Pause and try

Question 5 · Tracing

Here is a page and its script. The user types Biscuit and 3 and clicks Save. Predict the four lines in the console.

predict-values.html
<form id="pet-form">
  <label for="pet-name">Pet's name</label>
  <input id="pet-name" name="petName" type="text">
  <label for="pet-age">Age in years</label>
  <input id="pet-age" name="age" type="number">
  <button type="submit">Save</button>
</form>
predict-values.dom.ts
const form = document.querySelector<HTMLFormElement>("#pet-form");
if (form === null) {
  throw new Error("The page is missing the form");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(form);
  console.log(data.get("petName"));
  console.log(data.get("pet-name"));
  console.log(typeof data.get("age"));
  console.log(data.get("age") + "1");
});
Check your reasoning
Biscuit
null
string
31
  • Line 9: the input’s name is petName, so get("petName") finds Biscuit.
  • Line 10: "pet-name" is the input’s id, not its name. No input is named that, so get gives null.
  • Line 11: the age came from a number input, but form values are always strings: string.
  • Line 12: "3" + "1" joins two strings: 31, not 4.

Reread 20.3 Reading Values: input.value and FormData if any line differed.

Question 6 · Multiple choice

const nights = data.get("nights"); where data is a FormData. Which line does npx tsc accept straight after it?

  1. const total: number = nights * 80;
  2. const text: string = nights;
  3. const text: string = typeof nights === "string" ? nights : "";
  4. const count: number = Number(nights.trim());
Check your reasoning

C. nights is FormDataEntryValue | null. The conditional operator narrows it with typeof, so in the true branch it is a string, and the false branch gives "". Either way the result is a string. This is the textOf function written inline.

  • A is wrong: * needs numbers, and nights might be a string, a File, or null.
  • B is wrong: FormDataEntryValue | null is not assignable to string, because of the File and null members (TS2322).
  • D is wrong: trim is a string method, and nights might be null or a File, so the checker rejects the call before Number is reached.

Reread 20.3 Reading Values: input.value and FormData if you chose differently.

Section 4 of 8

20.4 Parsing Input into Typed Data

Number() turns a string into a number, but it is far too trusting for a form. Recall from Day 2 what it does with the things people really type: Number("") is 0, so an empty box becomes an age of zero; Number("fifteen") is NaN; Number("12.5") is a perfectly good number, but not a whole one. And a perfectly good whole number can still be wrong for the job: nobody signing up for a teen coding club is 9 or 200.

What you want is a function that takes the string from the form and gives back either a number you can trust or a message telling the user what to fix. That is exactly the shape of Day 16’s result union: { ok: true; value: … } when it worked, { ok: false; error: string } when it did not. Written once with a type parameter from Day 14, it works for any kind of value:

type Result<T> = { ok: true; value: T } | { ok: false; error: string };

Turning text into typed data, or reporting why it cannot be done, is called parsing. Checking that the data follows the rules (in range, not empty, and so on) is called validating. A parse function for a form field usually does both, and returns a Result.

Why a result union rather than Day 16’s throw? Because a bad answer in a form is not an accident. It is something users do every day, and the program’s job is to answer it with a message, not to stop. A result union makes that message an ordinary value, and the checker makes every caller look at ok before using value.

Worked example: Parsing an age

parse-age.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function parseAge(text: string): Result<number> {
  const trimmed = text.trim();
  if (trimmed === "") {
    return { ok: false, error: "Enter your age." };
  }
  const age = Number(trimmed);
  if (Number.isNaN(age)) {
    return { ok: false, error: "Age must be a number, such as 15." };
  }
  if (!Number.isInteger(age)) {
    return { ok: false, error: "Age must be a whole number." };
  }
  if (age < 13 || age > 120) {
    return { ok: false, error: "Age must be from 13 to 120." };
  }
  return { ok: true, value: age };
}

for (const text of ["15", " 40 ", "", "fifteen", "12.5", "9"]) {
  const result = parseAge(text);
  if (result.ok) {
    console.log(`"${text}" -> age ${result.value}`);
  } else {
    console.log(`"${text}" -> ${result.error}`);
  }
}
"15" -> age 15
" 40 " -> age 40
"" -> Enter your age.
"fifteen" -> Age must be a number, such as 15.
"12.5" -> Age must be a whole number.
"9" -> Age must be from 13 to 120.

Each check returns early (Day 8) with its own message, so the order of the checks is the order of the questions you would ask:

Line Question Example that stops here
4–7 Is there anything there at all? ""
8–11 Is it a number? "fifteen"
12–14 Is it a whole number? "12.5"
15–17 Is it in range? "9"
18 Everything passed "15", " 40 "

Line 12 uses Number.isInteger(value), which is true when value is a whole number and false for anything with a fraction (and for NaN). Lines 23 to 27 are the caller: result.ok is the discriminant from Day 9, so inside if (result.ok) the checker knows result.value exists, and in the else it knows result.error does. " 40 " passes because line 4 trims it first.

Notice that parseAge knows nothing about forms or pages. It takes a string and returns a value: a pure function, from Day 8. That is why you could run it with node. Now put the same function behind a form. The handler’s only jobs are to read the text, call parseAge, and show what came back:

age-form.html
<form id="age-form">
  <label for="age">Your age</label>
  <input id="age" name="age" type="text">
  <button type="submit">Check</button>
</form>
<p id="message"></p>
age-form.dom.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function parseAge(text: string): Result<number> {
  const trimmed = text.trim();
  if (trimmed === "") {
    return { ok: false, error: "Enter your age." };
  }
  const age = Number(trimmed);
  if (Number.isNaN(age)) {
    return { ok: false, error: "Age must be a number, such as 15." };
  }
  if (!Number.isInteger(age)) {
    return { ok: false, error: "Age must be a whole number." };
  }
  if (age < 13 || age > 120) {
    return { ok: false, error: "Age must be from 13 to 120." };
  }
  return { ok: true, value: age };
}

const form = document.querySelector<HTMLFormElement>("#age-form");
const ageInput = document.querySelector<HTMLInputElement>("#age");
const message = document.querySelector<HTMLParagraphElement>("#message");
if (form === null || ageInput === null || message === null) {
  throw new Error("The page is missing an element");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const result = parseAge(ageInput.value);
  if (result.ok) {
    message.textContent = `Welcome! Next year you will be ${result.value + 1}.`;
  } else {
    message.textContent = result.error;
  }
  console.log(message.textContent);
});

The user types fifteen and clicks Check, then changes it to 15 and clicks again. The console shows the message each time:

Age must be a number, such as 15.
Welcome! Next year you will be 16.

and the page ends with:

<p id="message">Welcome! Next year you will be 16.</p>

Line 32 can add 1 to result.value because it is a number; the parsing on lines 3 to 19 already turned the text into one. Keeping the parsing in its own function and out of the handler pays off on Day 22, when you will test functions like parseAge without a page.

What if a caller forgets to check ok?

parse-age-unchecked.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function parseAge(text: string): Result<number> {
  const age = Number(text.trim());
  if (text.trim() === "" || !Number.isInteger(age)) {
    return { ok: false, error: "Age must be a whole number." };
  }
  return { ok: true, value: age };
}

const result = parseAge("15");
console.log(result.value + 1);
parse-age-unchecked.ts:12:20 - error TS2339: Property 'value' does not exist on type 'Result<number>'.
  Property 'value' does not exist on type '{ ok: false; error: string; }'.

The second line says why: a failed result has no value. This is the result union doing its job, and it is the reason to prefer it to returning, say, NaN for bad input, which the checker would happily let you add 1 to. Wrap line 12 in if (result.ok), or delete the file.

Watch out

Letting Number("") through. This ticket parser skips the “is there anything there?” check:

parse-tickets-bug.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function parseTickets(text: string): Result<number> {
  const tickets = Number(text);
  if (Number.isNaN(tickets) || !Number.isInteger(tickets)) {
    return { ok: false, error: "Tickets must be a whole number." };
  }
  if (tickets < 0 || tickets > 6) {
    return { ok: false, error: "You can buy from 0 to 6 tickets." };
  }
  return { ok: true, value: tickets };
}

console.log(parseTickets("2"));
console.log(parseTickets("seven"));
console.log(parseTickets(""));
{ ok: true, value: 2 }
{ ok: false, error: 'Tickets must be a whole number.' }
{ ok: true, value: 0 }

The third line is the bug. An empty box is not a number, but Number("") is 0, so it passes the NaN check and the range check, and a user who forgot to type anything has “bought” zero tickets. The same happens with a box holding only spaces. Trim the text and check for "" before converting, as parseAge does on lines 4 to 7.

Key idea

A parse function turns a form’s string into Result<T>: { ok: true; value } with typed data, or { ok: false; error } with a message for the user. Check for empty text first, because Number("") is 0, not NaN.

Pause and try

Question 7 · Tracing

Predict the five lines this program prints.

predict-parse.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function parsePrice(text: string): Result<number> {
  const trimmed = text.trim();
  const price = Number(trimmed);
  if (trimmed === "" || Number.isNaN(price)) {
    return { ok: false, error: "not a price" };
  }
  if (price <= 0) {
    return { ok: false, error: "must be more than 0" };
  }
  return { ok: true, value: Math.round(price * 100) / 100 };
}

for (const text of ["4.5", "$4.50", " ", "0", "2.999"]) {
  const result = parsePrice(text);
  console.log(result.ok ? `ok ${result.value}` : `error: ${result.error}`);
}
Check your reasoning
ok 4.5
error: not a price
error: not a price
error: must be more than 0
ok 3
  • "4.5": a number, more than 0; Math.round(450) / 100 is 4.5.
  • "$4.50": the $ makes Number give NaN, so line 6 catches it.
  • " ": trimmed, it is "", so line 6 catches it before the NaN check matters (Number("") would have been 0).
  • "0": a number, but line 9 rejects anything that is not more than 0.
  • "2.999": Math.round(299.9) is 300, and 300 / 100 is 3, which shows as 3, not 3.00.

Line 17’s conditional operator narrows on result.ok, like an if. Reread 20.4 Parsing Input into Typed Data if any line differed.

Question 8 · Short answer

A classmate’s parseAge converts with Number(text) first and checks Number.isNaN next, with no empty-text check. Which input from the worked example now gets a different result, what is it, and why?

Check your reasoning

The empty string. Number("") is 0, which is not NaN, so it passes the “is it a number?” check and reaches the range check, which reports “Age must be from 13 to 120.” The user is told their age is out of range when they did not type one at all. (" 40 " still works, because Number ignores spaces at either end.) The message is confusing, and with a range that included 0, the empty box would even be accepted. Checking trimmed === "" first gives the right message: “Enter your age.”

Reread 20.4 Parsing Input into Typed Data if your answer differed.

Section 5 of 8

20.5 Validating a Whole Form: Every Error at Once

A booking form asks for a name, a number of nights, and a number of guests. Suppose the user leaves the name empty, types “two” for nights, and 9 for guests. A form that reports only the first problem says “Enter the name”. The user fixes it and sends again; now it says nights must be a number. They fix that; now guests is wrong. Three sends to learn three things the program knew the first time. A better form checks every field and reports every problem at once.

That changes the shape of the result. A whole form’s failure is not one message but one message per field that is wrong. Two tools from earlier days describe that exactly. A union of literal types (Day 9) names the fields, and Record<Field, string> (Day 7) is an object with a string for each field. But only the wrong fields have a message, so wrap it in Partial (Day 14), which makes every property optional:

type Field = "name" | "nights" | "guests";
type FieldErrors = Partial<Record<Field, string>>;

A FieldErrors is an object such as { nights: "…", guests: "…" }; an empty object {} means nothing is wrong. The form’s result is then its own discriminated union, with errors in place of error.

Worked example: Validating a booking

validate-booking.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

type Booking = { name: string; nights: number; guests: number };
type Field = "name" | "nights" | "guests";
type FieldErrors = Partial<Record<Field, string>>;
type BookingResult =
  { ok: true; value: Booking } | { ok: false; errors: FieldErrors };

function parseWholeNumber(
  text: string,
  label: string,
  min: number,
  max: number,
): Result<number> {
  const trimmed = text.trim();
  const value = Number(trimmed);
  if (trimmed === "" || !Number.isInteger(value)) {
    return { ok: false, error: `${label} must be a whole number.` };
  }
  if (value < min || value > max) {
    return { ok: false, error: `${label} must be from ${min} to ${max}.` };
  }
  return { ok: true, value };
}

function validateBooking(input: Record<Field, string>): BookingResult {
  const errors: FieldErrors = {};
  const name = input.name.trim();
  if (name === "") {
    errors.name = "Enter the name for the booking.";
  }
  const nights = parseWholeNumber(input.nights, "Nights", 1, 14);
  if (!nights.ok) {
    errors.nights = nights.error;
  }
  const guests = parseWholeNumber(input.guests, "Guests", 1, 4);
  if (!guests.ok) {
    errors.guests = guests.error;
  }
  if (name === "" || !nights.ok || !guests.ok) {
    return { ok: false, errors };
  }
  return {
    ok: true,
    value: { name, nights: nights.value, guests: guests.value },
  };
}

const good = validateBooking({ name: " Ana Lee ", nights: "3", guests: "2" });
console.log(good);

const bad = validateBooking({ name: "", nights: "two", guests: "9" });
if (!bad.ok) {
  for (const [field, message] of Object.entries(bad.errors)) {
    console.log(`${field}: ${message}`);
  }
}
{ ok: true, value: { name: 'Ana Lee', nights: 3, guests: 2 } }
name: Enter the name for the booking.
nights: Nights must be a whole number.
guests: Guests must be from 1 to 4.
Line What it does
6–7 The form’s result: a Booking on success, or the FieldErrors on failure
9–24 One parse function for any whole number in a range; the label makes its messages fit the field
27 Starts with no errors
28–39 Checks each field and records its message. Nothing returns early here, so every field is checked
40–42 If anything failed, return all the messages together
43–46 Otherwise build the Booking from the parsed values

Line 40 is where the checker earns its keep. After if (name === "" || !nights.ok || !guests.ok) return …;, the rest of the function runs only when all three passed, and the checker follows that: on line 45, nights and guests are narrowed to their ok: true members, so nights.value is allowed. Delete || !guests.ok from line 40 and npx tsc rejects guests.value on line 45, because a failed guests could still reach it.

For the second booking, all three checks fail, and lines 54 to 56 print every message with Day 7’s Object.entries. The first booking passes; name is trimmed on line 28, so the stored name has no spaces.

The function takes a Record<Field, string>: one string per field, which is exactly what you get from a form after reading each field with textOf from 20.3. Because it only takes strings and returns a value, you can try it with node before there is any page at all.

Watch out

Returning at the first error. Day 8 taught you to return early, and for a single value that is right. For a whole form it hides problems. This version returns as soon as anything is wrong:

validate-first-only.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

type Booking = { name: string; nights: number; guests: number };

function parseWholeNumber(
  text: string,
  label: string,
  min: number,
  max: number,
): Result<number> {
  const trimmed = text.trim();
  const value = Number(trimmed);
  if (trimmed === "" || !Number.isInteger(value)) {
    return { ok: false, error: `${label} must be a whole number.` };
  }
  if (value < min || value > max) {
    return { ok: false, error: `${label} must be from ${min} to ${max}.` };
  }
  return { ok: true, value };
}

function validateBooking(
  name: string,
  nightsText: string,
  guestsText: string,
): Result<Booking> {
  if (name.trim() === "") {
    return { ok: false, error: "Enter the name for the booking." };
  }
  const nights = parseWholeNumber(nightsText, "Nights", 1, 14);
  if (!nights.ok) {
    return nights;
  }
  const guests = parseWholeNumber(guestsText, "Guests", 1, 4);
  if (!guests.ok) {
    return guests;
  }
  return {
    ok: true,
    value: { name: name.trim(), nights: nights.value, guests: guests.value },
  };
}

console.log(validateBooking("", "two", "9"));
console.log(validateBooking("Ana Lee", "two", "9"));
console.log(validateBooking("Ana Lee", "3", "9"));
{ ok: false, error: 'Enter the name for the booking.' }
{ ok: false, error: 'Nights must be a whole number.' }
{ ok: false, error: 'Guests must be from 1 to 4.' }

Each line is one more send by the same user, fixing one field at a time. All three problems were there from the start. Check every field, collect the messages, and decide only at the end, as validateBooking does. (Lines 32 and 36 here show a neat trick, though: a failed Result<number> has no value, so it is also a valid failed Result<Booking> and can be returned as it is.)

Key idea

To validate a whole form, check every field, put each field’s message in a Partial<Record<Field, string>>, and only at the end return either the typed data or all the messages at once.

Pause and try

Question 9 · Tracing

This program uses the same parseWholeNumber as the worked example, with a function that returns only the errors. Predict the three lines it prints.

predict-errors.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

type Field = "name" | "nights" | "guests";
type FieldErrors = Partial<Record<Field, string>>;

function parseWholeNumber(
  text: string,
  label: string,
  min: number,
  max: number,
): Result<number> {
  const trimmed = text.trim();
  const value = Number(trimmed);
  if (trimmed === "" || !Number.isInteger(value)) {
    return { ok: false, error: `${label} must be a whole number.` };
  }
  if (value < min || value > max) {
    return { ok: false, error: `${label} must be from ${min} to ${max}.` };
  }
  return { ok: true, value };
}

function findErrors(input: Record<Field, string>): FieldErrors {
  const errors: FieldErrors = {};
  if (input.name.trim() === "") {
    errors.name = "Enter the name for the booking.";
  }
  const nights = parseWholeNumber(input.nights, "Nights", 1, 14);
  if (!nights.ok) {
    errors.nights = nights.error;
  }
  const guests = parseWholeNumber(input.guests, "Guests", 1, 4);
  if (!guests.ok) {
    errors.guests = guests.error;
  }
  return errors;
}

const errors = findErrors({ name: "  ", nights: "14", guests: "2.5" });
console.log(Object.keys(errors).length);
console.log(errors.nights ?? "nights ok");
console.log(errors.guests ?? "guests ok");
Check your reasoning
2
nights ok
Guests must be a whole number.
  • " " trims to "", so errors.name is set.
  • "14" is a whole number from 1 to 14 (the range includes both ends), so nights passes and errors.nights is never set.
  • "2.5" is a number but not a whole one, so errors.guests is set.

Two properties were set, so Object.keys(errors).length is 2. errors.nights is undefined, so ?? gives "nights ok"; errors.guests holds its message.

Reread 20.5 Validating a Whole Form: Every Error at Once if any line differed.

Question 10 · Short answer

Explain why FieldErrors is Partial<Record<Field, string>> and not just Record<Field, string>. What would go wrong on line 27 of validate-booking.ts with the second type?

Check your reasoning

Record<Field, string> says the object always has all three properties, each a string. But a form with only one wrong field has only one message, and a form with no wrong fields has none. Partial makes each property optional, so {} and { nights: "…" } are both valid FieldErrors.

With Record<Field, string>, line 27, const errors: FieldErrors = {};, would be rejected: an empty object is missing the name, nights, and guests properties that the type requires. You would have to fill them with something like "", and then every reader would have to remember that "" means “no error”.

Reread 20.5 Validating a Whole Form: Every Error at Once if your answer differed.

Section 6 of 8

20.6 Showing Errors Next to Each Field

You now have the messages. Where do they go? Not into console.log, which users never see, and not into one paragraph at the bottom of the page, which they have to match back to the fields. Each message goes right after its field, in an element of its own. The user looks at the field and sees what is wrong with it.

That is enough for a sighted user. For someone using a screen reader, three more things matter, and each is one HTML attribute:

  • aria-live="polite" on the element that will hold the message. It makes the element a live region: whenever its text changes, the screen reader reads out the new text as soon as it finishes what it is saying (that is the “polite” part). Without it, the message appears silently and a user who cannot see it never knows the form failed. The live region must already be on the page, empty, before the message is written into it; screen readers watch the regions that exist, and an element created and filled in one go is often missed.
  • aria-describedby on the input, naming the message element’s id. When the user moves to the input later, the screen reader reads its label and then the message: “Nights, edit text, Nights must be a whole number.”
  • aria-invalid="true" on an input that is wrong, set by your script with setAttribute and taken away with removeAttribute(name), which deletes an attribute from an element. The screen reader then says “invalid entry” for that field. (Pages often also style [aria-invalid="true"] with a red border, which you could add to style.css.)

aria- attributes change nothing you can see. They are information for programs like screen readers, which is why they are easy to forget and important to remember.

Worked example: A booking form that shows its errors

The page gives each input an empty message paragraph right after it, already live and already linked:

booking.html
<form id="booking">
  <label for="name">Name</label>
  <input id="name" name="name" type="text" aria-describedby="name-error">
  <p id="name-error" class="error" aria-live="polite"></p>

  <label for="nights">Nights</label>
  <input id="nights" name="nights" type="text" aria-describedby="nights-error">
  <p id="nights-error" class="error" aria-live="polite"></p>

  <label for="guests">Guests</label>
  <input id="guests" name="guests" type="text" aria-describedby="guests-error">
  <p id="guests-error" class="error" aria-live="polite"></p>

  <button type="submit">Book</button>
</form>
<p id="confirmation" aria-live="polite"></p>

The script’s first 47 lines are validate-booking.ts from 20.5 without its test calls. The rest is new:

booking.dom.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

type Booking = { name: string; nights: number; guests: number };
type Field = "name" | "nights" | "guests";
type FieldErrors = Partial<Record<Field, string>>;
type BookingResult =
  { ok: true; value: Booking } | { ok: false; errors: FieldErrors };

function parseWholeNumber(
  text: string,
  label: string,
  min: number,
  max: number,
): Result<number> {
  const trimmed = text.trim();
  const value = Number(trimmed);
  if (trimmed === "" || !Number.isInteger(value)) {
    return { ok: false, error: `${label} must be a whole number.` };
  }
  if (value < min || value > max) {
    return { ok: false, error: `${label} must be from ${min} to ${max}.` };
  }
  return { ok: true, value };
}

function validateBooking(input: Record<Field, string>): BookingResult {
  const errors: FieldErrors = {};
  const name = input.name.trim();
  if (name === "") {
    errors.name = "Enter the name for the booking.";
  }
  const nights = parseWholeNumber(input.nights, "Nights", 1, 14);
  if (!nights.ok) {
    errors.nights = nights.error;
  }
  const guests = parseWholeNumber(input.guests, "Guests", 1, 4);
  if (!guests.ok) {
    errors.guests = guests.error;
  }
  if (name === "" || !nights.ok || !guests.ok) {
    return { ok: false, errors };
  }
  return {
    ok: true,
    value: { name, nights: nights.value, guests: guests.value },
  };
}

function textOf(data: FormData, name: string): string {
  const value = data.get(name);
  return typeof value === "string" ? value : "";
}

const fields: Field[] = ["name", "nights", "guests"];

function showErrors(errors: FieldErrors): void {
  for (const field of fields) {
    const input = document.querySelector<HTMLInputElement>(`#${field}`);
    const errorText = document.querySelector<HTMLParagraphElement>(
      `#${field}-error`,
    );
    if (input === null || errorText === null) {
      continue;
    }
    const message = errors[field];
    if (message === undefined) {
      errorText.textContent = "";
      input.removeAttribute("aria-invalid");
    } else {
      errorText.textContent = message;
      input.setAttribute("aria-invalid", "true");
    }
  }
}

const form = document.querySelector<HTMLFormElement>("#booking");
const confirmation =
  document.querySelector<HTMLParagraphElement>("#confirmation");
if (form === null || confirmation === null) {
  throw new Error("The page is missing the form or the confirmation");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(form);
  const result = validateBooking({
    name: textOf(data, "name"),
    nights: textOf(data, "nights"),
    guests: textOf(data, "guests"),
  });
  if (result.ok) {
    showErrors({});
    const { name, nights, guests } = result.value;
    confirmation.textContent = `Booked for ${name}: ${nights} nights, ${guests} guests.`;
  } else {
    showErrors(result.errors);
    confirmation.textContent = "";
  }
});
Line What it does
49–52 textOf from 20.3
54 The fields, in page order, so showErrors can visit each one
56–74 For each field, finds its input (#nights) and its message (#nights-error) with a template literal, then sets or clears both
66–68 No message for this field: empty the paragraph and remove aria-invalid
69–72 A message: show it and mark the input invalid
85–90 Reads the form and validates it in one call
91–94 Success: clear every error (showErrors({})), destructure the booking (Day 7), and confirm it
95–98 Failure: show the errors and clear any old confirmation

The user types Ana Lee, two and 9 and clicks Book. The page becomes:

<form id="booking">
  <label for="name">Name</label>
  <input id="name" name="name" type="text" aria-describedby="name-error" />
  <p id="name-error" class="error" aria-live="polite"></p>

  <label for="nights">Nights</label>
  <input id="nights" name="nights" type="text" aria-describedby="nights-error" aria-invalid="true" />
  <p id="nights-error" class="error" aria-live="polite">Nights must be a whole number.</p>

  <label for="guests">Guests</label>
  <input id="guests" name="guests" type="text" aria-describedby="guests-error" aria-invalid="true" />
  <p id="guests-error" class="error" aria-live="polite">Guests must be from 1 to 4.</p>

  <button type="submit">Book</button>
</form>
<p id="confirmation" aria-live="polite"></p>

Both messages appear under their own fields, both inputs are marked invalid, and a screen reader announces both messages. The name was fine, so its paragraph stays empty.

Now vary the second send. The user changes nights to 3 and guests to 2 and clicks Book again (the file booking-fixed.dom.ts is the same script, run with both sends). This time result.ok is true, so line 92 calls showErrors({}): every field has no message, so every paragraph is emptied and every aria-invalid removed. The form is back to exactly the markup in booking.html, and the confirmation reads:

<p id="confirmation" aria-live="polite">Booked for Ana Lee: 3 nights, 2 guests.</p>

The two sends show why showErrors visits every field, not only the ones with errors: clearing is as much its job as showing.

Watch out

Only ever adding messages. A shorter showErrors that only handles fields with a message looks reasonable:

const message = errors[field];
if (message !== undefined) {
  errorText.textContent = message;
  input.setAttribute("aria-invalid", "true");
}

Run the same two sends with this version (booking-stale.dom.ts). After the second send, the confirmation says “Booked for Ana Lee: 3 nights, 2 guests.” while the old “Nights must be a whole number.” and “Guests must be from 1 to 4.” are still under the fields, and both inputs are still aria-invalid="true". Nothing ever cleared them. A field with no error must have its message emptied and its aria-invalid removed every time, as lines 66 to 68 do.

Key idea

Put each field’s message in an empty element right after it, marked aria-live="polite" so screen readers announce it, and point the input at it with aria-describedby. On every send, set or clear every field’s message and aria-invalid.

Pause and try

Question 11 · Multiple choice

A page should announce “Email is missing an @.” to screen reader users when the form fails. Which approach does that reliably?

  1. On failure, create a new <p>, give it aria-live="polite" and the message, and append it after the input.
  2. Have an empty <p id="email-error" aria-live="polite"></p> in the page from the start, and set its textContent on failure.
  3. Have an empty <p id="email-error"></p> in the page from the start, and set its textContent on failure.
  4. Call console.log("Email is missing an @.") on failure.
Check your reasoning

B. A live region is announced when its text changes, and screen readers watch the live regions that are already on the page. An empty live region from the start, filled in later, is the reliable pattern.

  • A is wrong: the region is created and filled in one step, so many screen readers never noticed it existed before it had text, and miss the announcement. It also adds a new paragraph on every failed send.
  • C is wrong: the text appears on screen, but without aria-live nothing is announced.
  • D is wrong: the console is for developers; users, with or without a screen reader, never see it.

Reread 20.6 Showing Errors Next to Each Field if you chose differently.

Question 12 · Tracing

With booking.html and booking.dom.ts, the user leaves Name empty, types 3 for nights and 4 for guests, and clicks Book. Which message paragraphs have text, which inputs have aria-invalid="true", and what does the confirmation say?

Check your reasoning
  • #name-error holds “Enter the name for the booking.” and the name input has aria-invalid="true".
  • #nights-error and #guests-error are empty, and neither of those inputs has aria-invalid: 3 is within 1 to 14 and 4 is within 1 to 4 (both ranges include their ends).
  • The confirmation is empty: result.ok is false, so line 97 clears it.

showErrors visits all three fields: one gets a message, two get cleared. Reread 20.6 Showing Errors Next to Each Field if your answer differed.

Section 7 of 8

20.7 Built-in Validation Attributes and Their Limits

Browsers can do some checking without any script at all. Add an attribute to an input, and the browser checks it when the form is sent:

Attribute The browser blocks the send when…
required the input is empty
type="email" the input is not empty and does not look like an email address
type="number" with min="13" and max="120" the number is below min or above max

(There are more, such as minlength, maxlength and pattern, which work in the same way.) When a check fails, the browser does not fire submit at all. It shows a small bubble next to the first bad field with a message of its own, such as “Please fill out this field.”, and puts the cursor there. Your listener never runs. These checks are called built-in validation.

Worked example: What the browser lets through

built-in.html
<form id="join">
  <label for="name">Name</label>
  <input id="name" name="name" type="text" required>
  <label for="email">Email</label>
  <input id="email" name="email" type="email" required>
  <label for="age">Age</label>
  <input id="age" name="age" type="number" min="13" max="120" required>
  <button type="submit">Join</button>
</form>
built-in.dom.ts
const form = document.querySelector<HTMLFormElement>("#join");
if (form === null) {
  throw new Error("The page is missing the form");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(form);
  const name = data.get("name");
  const email = data.get("email");
  const age = data.get("age");
  console.log(
    `name: "${name}", email: "${email}", age: "${age}" (${typeof age})`,
  );
});

The user tries to send four times:

Send Name Email Age What happens
1 (empty) (empty) (empty) Blocked: required fields are empty
2 three spaces sam@ 15 Blocked: sam@ has nothing after the @
3 three spaces sam@x 15 Sent
4 three spaces sam@x 9 Blocked: 9 is below min="13"

Only the third send reaches the listener, and the console shows its one line:

name: "   ", email: "sam@x", age: "15" (string)

Look hard at that one line, because it is the list of what built-in validation cannot do:

  • required accepts spaces. Three spaces are not empty, so the “name” was accepted. Your own check, trim() then === "", catches it.
  • type="email" is loose. sam@x passes: the browser only checks for some text, an @, and more text. A real address needs a dot in the part after the @.
  • The value is still a string. type="number" and min checked the number, but age arrives as "15", and you still have to convert it.
  • min and max do not make a field required. An empty number input with min but no required is sent as "" (Question 13 shows this).
  • The messages are the browser’s. Their wording and look differ between browsers, and they disappear when the user clicks elsewhere. You cannot put them in your own aria-live paragraphs.
  • Rules that involve two fields cannot be written as attributes: “the two passwords match”, “the end date is after the start date”.
  • Anyone can turn them off. The attributes are part of the page, and a user can remove them in the browser’s developer tools. One day your app’s data may go to a server, and the server must check everything again, because it cannot trust what a browser sends.

So the attributes are a first, free layer of help, never the whole of your validation. Many forms keep them for what they do well (type="email" gives a phone a keyboard with an @ key; required tells a screen reader the field is required) and switch off the browser’s checking with the novalidate attribute on the <form>. Then every send reaches your submit listener, and your own messages, next to the fields and announced by screen readers, are the only ones the user sees. The Putting it together page does exactly that.

Here is a stricter email check of your own, built only from Day 3’s string methods:

looks-like-email.ts
function looksLikeEmail(text: string): boolean {
  const at = text.indexOf("@");
  if (at < 1 || text.includes(" ")) {
    return false;
  }
  const domain = text.slice(at + 1);
  return (
    domain.includes(".") &&
    !domain.includes("@") &&
    !domain.startsWith(".") &&
    domain.at(-1) !== "."
  );
}

for (const text of [
  "sam@example.com",
  "sam@x",
  "@example.com",
  "sam@example.",
  "sam @example.com",
]) {
  console.log(`${text}: ${looksLikeEmail(text)}`);
}
sam@example.com: true
sam@x: false
@example.com: false
sam@example.: false
sam @example.com: false

It wants at least one character before the @ (line 3: at < 1 also covers “no @ at all”, where indexOf gives -1), no spaces, and a domain after the @ that has a dot that is neither its first nor its last character, and no second @. It still cannot tell whether the address exists; only sending an email to it can do that. No check can, so do not try to be perfect: catch the typos, and accept the rest.

Watch out

Trusting the attributes and skipping your own checks. A form with required and type="email" looks finished, and in a quick test with sensible answers it is. But every gap in the list above is a way for bad data to reach your code: spaces for a name, sam@x for an email, and strings for numbers. Always parse and validate in your script as well, as in 20.4 and 20.5.

Key idea

required, type="email", min and max make the browser block a send and show its own message, so your submit listener runs only when they pass. They are loose, they leave values as strings, and they can be switched off, so your own validation must always run too.

Pause and try

Question 13 · Tracing

The user types 0 for the quantity and clicks Order; types Kim for the name and clicks again; changes the quantity to 10 and clicks again; then empties the quantity box and clicks once more. Predict every line in the console.

predict-built-in.html
<form id="order">
  <label for="customer">Name</label>
  <input id="customer" name="customer" type="text" required>
  <label for="quantity">Quantity</label>
  <input id="quantity" name="quantity" type="number" min="1" max="10">
  <button type="submit">Order</button>
</form>
predict-built-in.dom.ts
const form = document.querySelector<HTMLFormElement>("#order");
if (form === null) {
  throw new Error("The page is missing the form");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(form);
  console.log(`Order: ${data.get("customer")} x "${data.get("quantity")}"`);
});
Check your reasoning
Order: Kim x "10"
Order: Kim x ""
  • Send 1 is blocked twice over: the name is required and empty, and 0 is below min="1".
  • Send 2 is blocked: the name is fine now, but 0 is still below min.
  • Send 3 passes: Kim, and 10 is within 1 to 10 (max includes 10).
  • Send 4 passes: the quantity has no required, and min and max only check a number that is there. An empty box is sent as "".

The last line is the lesson: your own parsing must still reject an empty quantity. Reread 20.7 Built-in Validation Attributes and Their Limits if your answer differed.

Question 14 · Short answer

A teammate says: “Our sign-up form has required on every field and type="email" on the email box, so we can delete the validateSignUp function.” Give three reasons to keep it.

Check your reasoning

Any three of these:

  • required accepts a name made only of spaces.
  • type="email" accepts addresses such as sam@x.
  • The values are still strings; something has to turn the age into a number, and check it is a whole number in range.
  • Built-in validation can be switched off (novalidate, or the developer tools), so it cannot be trusted.
  • The browser’s messages cannot be placed next to the fields or announced through your live regions.
  • Rules across fields (such as two matching passwords) cannot be written as attributes.

Reread 20.7 Built-in Validation Attributes and Their Limits if your answer differed.

Section 8 of 8

20.8 Results as the User Types: the input Event

A unit converter, a tip calculator, or a “characters left” counter should not need a button. The result should change as the user types. For that, the browser fires an input event on an input every time its value changes: each key typed, each character deleted, each paste. Listen for it exactly as you listen for click, and do the same three steps each time: read the value, parse it, show the result.

(There is also a change event, which fires only once the user has finished changing the value and leaves the box. It is useful when updating on every key would be too much.)

Worked example: Kilometres to miles as you type

live-convert.html
<label for="km">Distance in kilometres</label>
<input id="km" name="km" type="text" aria-describedby="miles">
<p id="miles" aria-live="polite">Type a distance.</p>
live-convert.dom.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function parseDistance(text: string): Result<number> {
  const trimmed = text.trim();
  const km = Number(trimmed);
  if (trimmed === "" || Number.isNaN(km)) {
    return { ok: false, error: "Type a distance, such as 5 or 42.2." };
  }
  if (km < 0) {
    return { ok: false, error: "A distance cannot be negative." };
  }
  return { ok: true, value: km };
}

const kmInput = document.querySelector<HTMLInputElement>("#km");
const miles = document.querySelector<HTMLParagraphElement>("#miles");
if (kmInput === null || miles === null) {
  throw new Error("The page is missing the input or the result");
}

kmInput.addEventListener("input", () => {
  const result = parseDistance(kmInput.value);
  if (result.ok) {
    miles.textContent = `${result.value} km is ${(result.value * 0.621371).toFixed(1)} miles.`;
  } else {
    miles.textContent = result.error;
  }
  console.log(miles.textContent);
});

The user types 5, then a k after it, then replaces it all with 42.2. The console shows the paragraph after each change:

5 km is 3.1 miles.
Type a distance, such as 5 or 42.2.
42.2 km is 26.2 miles.

There is no form and no submit here, so no preventDefault either: an input event has no default action to cancel. Line 21 attaches the listener to the input itself, and line 22 reads kmInput.value each time, so it always sees the latest text. The parsing is a Result function like parseAge, and the paragraph is a live region linked to the input with aria-describedby, so a screen reader user hears each new result.

Now vary where the listener goes. input events bubble, like Day 19’s clicks: an input event on any field in a form also reaches the <form>. So one listener on the form, form.addEventListener("input", …), runs whenever any of its fields changes. That is Day 19’s event delegation, and it is what a form with several inputs (such as a tip calculator) needs: on every change, read all the fields with FormData and recompute.

Watch out

Scolding the user while they type. Run full validation with error messages on every input event, and an email field turns red with “Enter an email address” the moment the user types the first s. The user has done nothing wrong yet; they just have not finished. Live updates suit results (a converted number, a total) and gentle hints. Show full error messages when the user sends the form, or on change once they leave the field. A polite live region that changes on every key can also be noisy for screen reader users, so keep live messages short.

Key idea

The input event fires on every change to a field’s value; read, parse and show the result in its listener. It bubbles, so one listener on a form covers all its fields.

Pause and try

Question 15 · Tracing

With live-convert.html and live-convert.dom.ts, the user types -3, then deletes everything so the box is empty. What does the paragraph show after each of the two changes? (The - alone is a change too: start from after the 3.)

Check your reasoning
  • After -3: Number("-3") is -3, which is a number, so line 6 does not stop it; line 9 does: A distance cannot be negative.
  • After deleting everything: the value is "", so line 6 stops it: Type a distance, such as 5 or 42.2. Without the trimmed === "" check, Number("") would be 0 and the page would claim “0 km is 0.0 miles.”

(The - on its own, typed first, also fired an input event: Number("-") is NaN, so the paragraph briefly showed the “Type a distance” message.) Reread 20.8 Results as the User Types: the input Event if your answer differed.

Wrap-up · 1 of 8

Putting it together

A trip expense tracker: the user adds expenses one at a time, each with a description and an amount, and the page lists them with a running total. The form has novalidate, so the script’s own messages are the only ones the user sees, and required is kept so that screen readers announce the fields as required.

expenses.html
<form id="expense-form" novalidate>
  <label for="description">What was it for?</label>
  <input id="description" name="description" type="text" required aria-describedby="description-error">
  <p id="description-error" class="error" aria-live="polite"></p>

  <label for="amount">Amount in dollars</label>
  <input id="amount" name="amount" type="text" required aria-describedby="amount-error">
  <p id="amount-error" class="error" aria-live="polite"></p>

  <button type="submit">Add expense</button>
</form>
<ul id="expenses"></ul>
<p id="total">Total: $0.00</p>
expenses.dom.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

type Expense = { description: string; amount: number };
type Field = "description" | "amount";
type FieldErrors = Partial<Record<Field, string>>;
type ExpenseResult =
  { ok: true; value: Expense } | { ok: false; errors: FieldErrors };

function parseAmount(text: string): Result<number> {
  const trimmed = text.trim();
  const amount = Number(trimmed);
  if (trimmed === "" || Number.isNaN(amount)) {
    return { ok: false, error: "Enter an amount, such as 12.50." };
  }
  if (amount <= 0) {
    return { ok: false, error: "The amount must be more than 0." };
  }
  return { ok: true, value: Math.round(amount * 100) / 100 };
}

function validateExpense(
  descriptionText: string,
  amountText: string,
): ExpenseResult {
  const errors: FieldErrors = {};
  const description = descriptionText.trim();
  if (description === "") {
    errors.description = "Say what the money was for.";
  } else if (description.length > 40) {
    errors.description = "Keep the description to 40 characters.";
  }
  const amount = parseAmount(amountText);
  if (!amount.ok) {
    errors.amount = amount.error;
  }
  if (errors.description !== undefined || !amount.ok) {
    return { ok: false, errors };
  }
  return { ok: true, value: { description, amount: amount.value } };
}

function textOf(data: FormData, name: string): string {
  const value = data.get(name);
  return typeof value === "string" ? value : "";
}

const fields: Field[] = ["description", "amount"];

function showErrors(errors: FieldErrors): void {
  for (const field of fields) {
    const input = document.querySelector<HTMLInputElement>(`#${field}`);
    const errorText = document.querySelector<HTMLParagraphElement>(
      `#${field}-error`,
    );
    if (input === null || errorText === null) {
      continue;
    }
    const message = errors[field];
    if (message === undefined) {
      errorText.textContent = "";
      input.removeAttribute("aria-invalid");
    } else {
      errorText.textContent = message;
      input.setAttribute("aria-invalid", "true");
    }
  }
}

const expenses: Expense[] = [];

function render(): void {
  const list = document.querySelector<HTMLUListElement>("#expenses");
  const total = document.querySelector<HTMLParagraphElement>("#total");
  if (list === null || total === null) {
    return;
  }
  list.textContent = "";
  for (const expense of expenses) {
    const item = document.createElement("li");
    item.textContent = `${expense.description}: $${expense.amount.toFixed(2)}`;
    list.append(item);
  }
  const sum = expenses.reduce(
    (running, expense) => running + expense.amount,
    0,
  );
  total.textContent = `Total: $${sum.toFixed(2)}`;
}

const form = document.querySelector<HTMLFormElement>("#expense-form");
if (form === null) {
  throw new Error("The page is missing the form");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(form);
  const result = validateExpense(
    textOf(data, "description"),
    textOf(data, "amount"),
  );
  if (!result.ok) {
    showErrors(result.errors);
    console.log(`Not added: ${Object.values(result.errors).join(" ")}`);
    document.querySelector<HTMLInputElement>("[aria-invalid]")?.focus();
    return;
  }
  showErrors({});
  expenses.push(result.value);
  render();
  form.reset();
  console.log(`Added: ${result.value.description}`);
});

The user clicks Add expense with both boxes empty; types Bus tickets and 12.5 and clicks; types Lunch and -3 and clicks; changes the amount to 8.25 and clicks. The console shows:

Not added: Say what the money was for. Enter an amount, such as 12.50.
Added: Bus tickets
Not added: The amount must be more than 0.
Added: Lunch

and the page ends with both errors cleared, and:

<ul id="expenses">
  <li>Bus tickets: $12.50</li>
  <li>Lunch: $8.25</li>
</ul>
<p id="total">Total: $20.75</p>

Follow the third send, Lunch and -3, through the program:

Line What happens Idea
95–96 submit fires on the form, because novalidate turned off the browser’s checks; no new page loads 20.2, 20.7
97–101 FormData reads both fields; textOf narrows each to a string: "Lunch" and "-3" 20.3
26–31 The description trims to "Lunch", which is neither empty nor over 40 characters: no message 20.5
32 parseAmount("-3"): a number, but line 15 rejects it, so the result is ok: false 20.4
33–38 The amount’s message is recorded, and the whole result is { ok: false, errors: { amount: … } } 20.5
103 showErrors empties the description’s message and fills the amount’s, setting its aria-invalid 20.6
104 Logs the messages, joined with Object.values 20.5
105 Moves the cursor to the first input marked invalid, so the user can fix it straight away 20.6

[aria-invalid] on line 105 is a CSS selector that matches any element having that attribute; ?. (Day 9) skips the call when there is none. On the fourth send everything passes: line 108 clears all messages, line 109 changes the state, line 110 renders the list and the total from that state as on Day 19, and form.reset() on line 111 empties every input in the form, ready for the next expense. render clears the list with textContent = "" before rebuilding it, and reduce (Day 11) adds the amounts. Line 18 rounds each amount to whole cents, so 12.5 is stored as 12.5 and shown as $12.50 by toFixed(2).

Every idea from today has one job. The markup gives each field a label, a name, and a live message slot. The submit listener, with preventDefault, is the one place the form is handled. The parse and validate functions turn strings into a typed Expense or a set of messages, and know nothing about the page. And showErrors and render put the outcome on the page, for every user.

Wrap-up · 2 of 8

Common mistakes

Today’s symptoms and messages in one place.

Message or symptom Usual cause Fix
The page flashes, the result vanishes, and ?name=… appears in the address No event.preventDefault() in the submit listener Call it on the first line of the listener
Total: 4010 instead of 50 Adding two value strings joins them Number() each value first, after parsing it
TS2322: Type 'FormDataEntryValue | null' is not assignable to type 'number'. Using get()’s result as a number Narrow to string (textOf), then parse
TS2339: Property 'trim' does not exist on type 'FormDataEntryValue'. Ruling out null but not File typeof value === "string"
get("…") gives null Asking for an input’s id instead of its name, or a missing name Use the name attribute
TS2339: Property 'value' does not exist on type 'Result<number>'. Using a result without checking ok if (result.ok) first
An empty box is accepted as 0 Number("") is 0 Trim and check for "" before converting
The user has to send the form once per mistake Validation returns at the first error Check every field, collect the messages, decide at the end
Old error messages stay after the field is fixed Only adding messages, never clearing them Set or clear every field’s message and aria-invalid each time
Screen reader users are not told the form failed No aria-live, or the region was created at the same moment as the text Put an empty aria-live="polite" element in the page from the start
Spaces accepted as a name, sam@x as an email Relying on required and type="email" Validate in your script too
Wrap-up · 3 of 8

Vocabulary

Term Definition Example
form A part of a page that collects typed answers and sends them together <form id="booking">…</form>
input A box the user types into; its name files its answer in the form <input id="age" name="age" type="text">
label The visible name of an input, linked by for = the input’s id <label for="age">Age</label>
screen reader A program that reads the page aloud for someone who cannot see it Announces “Age, edit text”
submit event Fired on a form when it is sent, by its button or by Enter form.addEventListener("submit", …)
default action What the browser does on its own after an event’s listeners run A form loads a new page
event.preventDefault() Cancels the default action First line of a submit listener
value An input’s current text, always a string ageInput.value is "15"
FormData A snapshot of a form’s named inputs; get(name) gives FormDataEntryValue | null new FormData(form).get("age")
parsing Turning text into typed data, or reporting why it cannot be done parseAge("15") gives { ok: true, value: 15 }
validating Checking that data follows the rules Age from 13 to 120
Number.isInteger true for a whole number, false otherwise (including NaN) Number.isInteger(12.5) is false
live region An element whose text changes are read out by screen readers <p aria-live="polite"></p>
aria-describedby Links an input to the element that describes it, such as its error message aria-describedby="age-error"
aria-invalid Tells screen readers an input’s value is wrong input.setAttribute("aria-invalid", "true")
built-in validation Checks the browser runs before submit, set by attributes required, type="email", min, max
novalidate A form attribute that turns built-in validation off <form novalidate>
input event Fired on every change to a field’s value kmInput.addEventListener("input", …)
Wrap-up · 4 of 8

Summary

  • A <form> holds <input>s, each with an id, a name, and a linked <label>. Sending the form fires submit on the form, whether by button or Enter; call event.preventDefault() first, or the browser loads a new page.
  • Every value from a form is a string: input.value is a string, and FormData’s get(name) is FormDataEntryValue | null, to be narrowed with typeof before use.
  • Parse each field with a pure function that returns Result<T>, checking empty text before Number(); validate a whole form by checking every field and returning either the typed data or a Partial<Record<Field, string>> of messages.
  • Show each message in an empty aria-live="polite" element right after its field, linked with aria-describedby, and set or clear every message and aria-invalid on each send.
  • required, type="email", min and max block bad sends with the browser’s own messages, but they are loose, leave values as strings, and can be switched off, so your own validation always runs too. The input event lets a page update its results as the user types.
Wrap-up · 5 of 8

Practice

Do these in your day20 Vite project. First make sure npx tsc prints nothing there; if a broken file from today is still in your Node folder (such as parse-age-unchecked.ts), or src/main.ts still holds a broken script such as form-data-number.dom.ts, fix it or delete it. Write the page and the script yourself, try every kind of bad input in the browser, and only then open the answer.

Question 16 · Short answer

Sign-up form. Build a form with a name, an email address, and an age. When it is sent, validate all three and show every problem at once as a list above or below the form. The name must not be empty, the email must pass a check like looksLikeEmail, and the age must be a whole number from 13 to 120. When everything is right, show “Welcome, Ana!” (with the user’s name).

Check your reasoning

One possible solution:

signup.html
<form id="signup" novalidate>
  <label for="name">Name</label>
  <input id="name" name="name" type="text" required>
  <label for="email">Email</label>
  <input id="email" name="email" type="email" required>
  <label for="age">Age</label>
  <input id="age" name="age" type="text" required>
  <button type="submit">Sign up</button>
</form>
<div aria-live="polite">
  <ul id="errors"></ul>
  <p id="welcome"></p>
</div>
signup.dom.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
type SignUp = { name: string; email: string; age: number };
type SignUpResult =
  { ok: true; value: SignUp } | { ok: false; errors: string[] };

function looksLikeEmail(text: string): boolean {
  const at = text.indexOf("@");
  if (at < 1 || text.includes(" ")) {
    return false;
  }
  const domain = text.slice(at + 1);
  return (
    domain.includes(".") &&
    !domain.includes("@") &&
    !domain.startsWith(".") &&
    domain.at(-1) !== "."
  );
}

function parseAge(text: string): Result<number> {
  const trimmed = text.trim();
  const age = Number(trimmed);
  if (trimmed === "" || !Number.isInteger(age)) {
    return { ok: false, error: "Age must be a whole number, such as 15." };
  }
  if (age < 13 || age > 120) {
    return { ok: false, error: "Age must be from 13 to 120." };
  }
  return { ok: true, value: age };
}

function validateSignUp(
  nameText: string,
  emailText: string,
  ageText: string,
): SignUpResult {
  const errors: string[] = [];
  const name = nameText.trim();
  const email = emailText.trim();
  if (name === "") {
    errors.push("Enter your name.");
  }
  if (!looksLikeEmail(email)) {
    errors.push("Enter an email address such as sam@example.com.");
  }
  const age = parseAge(ageText);
  if (!age.ok) {
    errors.push(age.error);
  }
  if (errors.length > 0 || !age.ok) {
    return { ok: false, errors };
  }
  return { ok: true, value: { name, email, age: age.value } };
}

function textOf(data: FormData, name: string): string {
  const value = data.get(name);
  return typeof value === "string" ? value : "";
}

const form = document.querySelector<HTMLFormElement>("#signup");
const errorList = document.querySelector<HTMLUListElement>("#errors");
const welcome = document.querySelector<HTMLParagraphElement>("#welcome");
if (form === null || errorList === null || welcome === null) {
  throw new Error("The page is missing an element");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(form);
  const result = validateSignUp(
    textOf(data, "name"),
    textOf(data, "email"),
    textOf(data, "age"),
  );
  errorList.textContent = "";
  welcome.textContent = "";
  if (!result.ok) {
    for (const message of result.errors) {
      const item = document.createElement("li");
      item.textContent = message;
      errorList.append(item);
    }
    return;
  }
  welcome.textContent = `Welcome, ${result.value.name}!`;
});

With a name of only spaces, sam@x and twelve, the list shows all three messages:

<ul id="errors">
  <li>Enter your name.</li>
  <li>Enter an email address such as sam@example.com.</li>
  <li>Age must be a whole number, such as 15.</li>
</ul>

Here the failure holds an array of messages, errors: string[], because the task asks for one list rather than a message next to each field; each check pushes its message, and nothing returns early until line 50. novalidate turns off the browser’s bubbles so that the list is the only feedback, and the list sits inside a <div aria-live="polite"> that is on the page from the start, so a screen reader announces the new items. Lines 76 and 77 clear the old list and welcome before every send, so fixed problems disappear.

Reread 20.5 Validating a Whole Form: Every Error at Once and 20.7 Built-in Validation Attributes and Their Limits if your page behaved differently.

Question 17 · Short answer

Tip calculator. Build a form with a bill amount and a tip percentage. As soon as both are valid, show the tip and the total, updating as the user types; while either is not valid, show a short hint instead. No button is needed.

Check your reasoning

One possible solution:

tip.html
<form id="tip-form" novalidate>
  <label for="bill">Bill in dollars</label>
  <input id="bill" name="bill" type="text" aria-describedby="tip-result">
  <label for="percent">Tip percentage</label>
  <input id="percent" name="percent" type="text" aria-describedby="tip-result">
</form>
<p id="tip-result" aria-live="polite">Enter the bill and a tip percentage.</p>
tip.dom.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function parseNumber(
  text: string,
  label: string,
  min: number,
  max: number,
): Result<number> {
  const trimmed = text.trim();
  const value = Number(trimmed);
  if (trimmed === "" || Number.isNaN(value)) {
    return { ok: false, error: `Enter the ${label} as a number.` };
  }
  if (value < min || value > max) {
    return { ok: false, error: `The ${label} must be from ${min} to ${max}.` };
  }
  return { ok: true, value };
}

function textOf(data: FormData, name: string): string {
  const value = data.get(name);
  return typeof value === "string" ? value : "";
}

const form = document.querySelector<HTMLFormElement>("#tip-form");
const output = document.querySelector<HTMLParagraphElement>("#tip-result");
if (form === null || output === null) {
  throw new Error("The page is missing the form or the result");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
});

form.addEventListener("input", () => {
  const data = new FormData(form);
  const bill = parseNumber(textOf(data, "bill"), "bill", 0.01, 10000);
  const percent = parseNumber(textOf(data, "percent"), "tip", 0, 100);
  if (!bill.ok) {
    output.textContent = bill.error;
  } else if (!percent.ok) {
    output.textContent = percent.error;
  } else {
    const tip = (bill.value * percent.value) / 100;
    const total = bill.value + tip;
    output.textContent = `Tip: $${tip.toFixed(2)}. Total: $${total.toFixed(2)}.`;
  }
  console.log(output.textContent);
});

Typing 48 for the bill, then 1o (a typo) and then 15 for the tip shows, after each change:

Enter the tip as a number.
Enter the tip as a number.
Tip: $7.20. Total: $55.20.

Line 35 puts one input listener on the form: input events bubble, so typing in either box runs it. Each time, it reads both fields with FormData and parses both with one parseNumber function whose label fits its messages to each field. The result paragraph is a live region linked to both inputs. Lines 31 to 33 still prevent the default action, because pressing Enter in a box would otherwise send the form and reload the page.

Reread 20.8 Results as the User Types: the input Event if your page behaved differently.

Question 18 · Short answer

Add a task. Add a form to Day 19’s task list so the user can add a task. Reject an empty title, a title over 60 characters, and a title already on the list (ignoring capitals), with the message next to the input. Clicking a task still toggles it done, using one listener on the list.

Check your reasoning

One possible solution:

tasks.html
<form id="new-task-form" novalidate>
  <label for="new-task">New task</label>
  <input id="new-task" name="title" type="text" required aria-describedby="new-task-error">
  <button type="submit">Add</button>
  <p id="new-task-error" class="error" aria-live="polite"></p>
</form>
<ul id="tasks"></ul>
tasks.dom.ts
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
type Task = { title: string; done: boolean };

const tasks: Task[] = [];

function parseTitle(text: string, existing: Task[]): Result<string> {
  const title = text.trim();
  if (title === "") {
    return { ok: false, error: "Type a task before you add it." };
  }
  if (title.length > 60) {
    return { ok: false, error: "Keep a task to 60 characters." };
  }
  const lower = title.toLowerCase();
  if (existing.some((task) => task.title.toLowerCase() === lower)) {
    return { ok: false, error: `"${title}" is already on the list.` };
  }
  return { ok: true, value: title };
}

function render(list: HTMLUListElement): void {
  list.textContent = "";
  for (const [index, task] of tasks.entries()) {
    const button = document.createElement("button");
    button.type = "button";
    button.textContent = task.title;
    button.setAttribute("data-index", String(index));
    button.setAttribute("aria-pressed", String(task.done));
    const item = document.createElement("li");
    if (task.done) {
      item.classList.add("done");
    }
    item.append(button);
    list.append(item);
  }
}

const form = document.querySelector<HTMLFormElement>("#new-task-form");
const input = document.querySelector<HTMLInputElement>("#new-task");
const error = document.querySelector<HTMLParagraphElement>("#new-task-error");
const list = document.querySelector<HTMLUListElement>("#tasks");
if (form === null || input === null || error === null || list === null) {
  throw new Error("The page is missing an element");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const result = parseTitle(input.value, tasks);
  if (!result.ok) {
    error.textContent = result.error;
    console.log(result.error);
    input.setAttribute("aria-invalid", "true");
    input.focus();
    return;
  }
  error.textContent = "";
  input.removeAttribute("aria-invalid");
  tasks.push({ title: result.value, done: false });
  render(list);
  form.reset();
  input.focus();
});

list.addEventListener("click", (event) => {
  if (!(event.target instanceof HTMLButtonElement)) {
    return;
  }
  const task = tasks[Number(event.target.getAttribute("data-index"))];
  if (task === undefined) {
    return;
  }
  task.done = !task.done;
  render(list);
});

Adding Buy milk, then spaces, then buy MILK, then Walk the dog, and clicking the first task logs the two rejections:

Type a task before you add it.
"buy MILK" is already on the list.

and leaves this list, with the error message empty again:

<ul id="tasks">
  <li class="done"><button type="button" data-index="0" aria-pressed="true">Buy milk</button></li>
  <li><button type="button" data-index="1" aria-pressed="false">Walk the dog</button></li>
</ul>

parseTitle returns a Result<string>: a title is text already, but it still needs trimming and checking. The duplicate check is Day 11’s some, comparing lowercase copies. The submit listener changes the state (tasks.push) and calls render, as Day 19’s buttons did; form.reset() empties the box and focus() puts the cursor back for the next task. Each task is a real <button>, so it works from the keyboard, and aria-pressed tells a screen reader whether it is done. The click listener on the list is Day 19’s delegation: it narrows event.target with instanceof and reads the button’s data-index.

Reread 20.4 Parsing Input into Typed Data and 20.6 Showing Errors Next to Each Field if your page behaved differently.

Wrap-up · 6 of 8

Review questions

Question 19 · Tracing

Tickets cost $2.50. The user types each of these into the box and clicks Buy after each: 4, then two spaces, then 2 with a space before and after it, then two. Predict the four console lines, and say which of them is a bug.

review-order.html
<form id="order">
  <label for="quantity">How many tickets?</label>
  <input id="quantity" name="quantity" type="text">
  <button type="submit">Buy</button>
</form>
<p id="total"></p>
review-order.dom.ts
const form = document.querySelector<HTMLFormElement>("#order");
const quantityInput = document.querySelector<HTMLInputElement>("#quantity");
const total = document.querySelector<HTMLParagraphElement>("#total");
if (form === null || quantityInput === null || total === null) {
  throw new Error("The page is missing an element");
}

const price = 2.5;

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const quantity = Number(quantityInput.value);
  if (Number.isNaN(quantity)) {
    total.textContent = "Not a number";
  } else {
    total.textContent = `Total: $${(quantity * price).toFixed(2)}`;
  }
  console.log(total.textContent);
});
Check your reasoning
Total: $10.00
Total: $0.00
Total: $5.00
Not a number
  • Number("4") is 4, and 4 × 2.5 is 10.
  • Number(" ") is 0: Day 2’s rule that blank text converts to 0. That is the bug: a user who typed nothing is charged nothing and told so as if it were a real order.
  • Number(" 2 ") ignores the outer spaces: 2 × 2.5 is 5.
  • Number("two") is NaN, which line 13 catches.

The fix is a parse function as in 20.4: trim, reject "", reject NaN, require a whole number of at least 1, and return a Result<number>.

Reread 20.4 Parsing Input into Typed Data if any line differed.

Question 20 · Debugging

This RSVP form is supposed to show one message under the field when the number of guests is not a whole number. The user types two and clicks Reply, then types 2.5 and clicks again, then types 2 and clicks again. After the third send the console says “Replied with 2 guests”, but the page still shows the error, twice. Find both bugs and fix them.

review-pile-up.html
<form id="rsvp">
  <label for="guests">Guests</label>
  <input id="guests" name="guests" type="text" aria-describedby="guests-error">
  <div id="guests-error" aria-live="polite"></div>
  <button type="submit">Reply</button>
</form>
review-pile-up.dom.ts
const form = document.querySelector<HTMLFormElement>("#rsvp");
const guestsInput = document.querySelector<HTMLInputElement>("#guests");
const guestsError = document.querySelector<HTMLDivElement>("#guests-error");
if (form === null || guestsInput === null || guestsError === null) {
  throw new Error("The page is missing an element");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const guests = Number(guestsInput.value.trim());
  if (guestsInput.value.trim() === "" || !Number.isInteger(guests)) {
    const message = document.createElement("p");
    message.textContent = "Guests must be a whole number.";
    guestsError.append(message);
    return;
  }
  console.log(`Replied with ${guests} guests`);
});
Check your reasoning

After the three sends, the message area is:

<div id="guests-error" aria-live="polite">
  <p>Guests must be a whole number.</p>
  <p>Guests must be a whole number.</p>
</div>
  • Bug 1: every failed send creates and appends a new paragraph (lines 12 to 14), so messages pile up instead of being replaced.
  • Bug 2: a successful send never clears the old messages, so the error stays after it has been fixed.

Set the live region’s text instead of appending to it, and clear it on success:

review-pile-up-fixed.dom.ts
const form = document.querySelector<HTMLFormElement>("#rsvp");
const guestsInput = document.querySelector<HTMLInputElement>("#guests");
const guestsError = document.querySelector<HTMLDivElement>("#guests-error");
if (form === null || guestsInput === null || guestsError === null) {
  throw new Error("The page is missing an element");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const guests = Number(guestsInput.value.trim());
  if (guestsInput.value.trim() === "" || !Number.isInteger(guests)) {
    guestsError.textContent = "Guests must be a whole number.";
    return;
  }
  guestsError.textContent = "";
  console.log(`Replied with ${guests} guests`);
});

After the same three sends, the region is empty again and the console still says Replied with 2 guests. Setting textContent also changes the text of an element that was already on the page, which is what makes the live region announce it reliably.

Reread 20.6 Showing Errors Next to Each Field if you found something different.

Question 21 · Tracing

A “change password” form has two boxes, the new password and the same password again. Predict the three lines this program prints. Which check here could not be done with built-in validation attributes?

review-password.ts
type PasswordErrors = { password?: string; confirm?: string };

function checkPasswords(password: string, confirm: string): PasswordErrors {
  const errors: PasswordErrors = {};
  if (password.length < 8) {
    errors.password = "Use at least 8 characters.";
  } else if (password.toLowerCase() === password) {
    errors.password = "Use at least one capital letter.";
  }
  if (confirm !== password) {
    errors.confirm = "The two passwords do not match.";
  }
  return errors;
}

const attempts: [string, string][] = [
  ["sunflower", "sunflower"],
  ["Sun", "sun"],
  ["Sunflower", "Sunflower "],
];
for (const [password, confirm] of attempts) {
  const errors = checkPasswords(password, confirm);
  console.log(`${errors.password ?? "-"} | ${errors.confirm ?? "-"}`);
}
Check your reasoning
Use at least one capital letter. | -
Use at least 8 characters. | The two passwords do not match.
- | The two passwords do not match.
  • "sunflower" is long enough, but lowercasing it changes nothing, so it has no capital letter. The two boxes match, so there is no confirm message, and ?? shows -.
  • "Sun" is too short; the else if is skipped, so only one password message. "sun" is not "Sun": !== compares exactly, capitals included.
  • "Sunflower" passes both password checks, but "Sunflower " has a trailing space, so the boxes do not match. (Whether to trim passwords is a design choice; many sites do not, because a space can be part of a password.)

The “do the two match?” check compares two fields, which no single input’s attribute can express. Both checks also run every time, so the user sees both problems at once.

Reread 20.5 Validating a Whole Form: Every Error at Once and 20.7 Built-in Validation Attributes and Their Limits if any line differed.

Question 22 · Debugging

This listener checks for null before calling trim(), but npx tsc still rejects it. Explain the message and fix the script.

review-file-entry.dom.ts
const form = document.querySelector<HTMLFormElement>("#stay");
const output = document.querySelector<HTMLParagraphElement>("#output");
if (form === null || output === null) {
  throw new Error("The page is missing the form or the output");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const nights = new FormData(form).get("nights");
  if (nights === null) {
    return;
  }
  output.textContent = `${Number(nights.trim()) + 1} days`;
});
review-file-entry.dom.ts:13:41 - error TS2339: Property 'trim' does not exist on type 'FormDataEntryValue'.
  Property 'trim' does not exist on type 'File'.
Check your reasoning

get returns FormDataEntryValue | null, and FormDataEntryValue is string | File. Line 10 rules out null, so on line 13 nights is string | File, and a File has no trim method; the second line of the message names that member. Narrow to the one member you want instead (only line 10 changes):

review-file-entry-fixed.dom.ts
const form = document.querySelector<HTMLFormElement>("#stay");
const output = document.querySelector<HTMLParagraphElement>("#output");
if (form === null || output === null) {
  throw new Error("The page is missing the form or the output");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const nights = new FormData(form).get("nights");
  if (typeof nights !== "string") {
    return;
  }
  output.textContent = `${Number(nights.trim()) + 1} days`;
});

typeof nights !== "string" rules out both null and File at once, so on line 13 nights is a string. On a page with a Nights box, typing 3 and sending the form shows:

<p id="output">4 days</p>

" 3 " trims to "3", which converts to 3, plus 1 is 4. This is exactly what textOf does.

Reread 20.3 Reading Values: input.value and FormData if you fixed it differently.

Question 23 · Multiple choice

In expenses.dom.ts, parseAmount and validateExpense take strings and return values, and never touch the page. Which is the best reason for writing them that way?

  1. Functions that touch the page cannot have return types.
  2. They can be run and checked on their own, with node or (on Day 22) with tests, without a browser or a form, and the handler stays short.
  3. FormData can only be used inside a function that returns void.
  4. It makes the browser’s built-in validation run first.
Check your reasoning

B. A pure function that turns strings into a Result can be called with any input you like and its answer printed or tested, which is how every parse function on this page was tried first. The submit listener then only reads the form, calls the function, and shows the outcome.

  • A is wrong: any function can declare a return type, including ones that change the page (showErrors returns void, and could return something else).
  • C is wrong: FormData can be used anywhere; textOf takes one and returns a string.
  • D is wrong: built-in validation depends on the attributes and novalidate, not on how your functions are written. In this page it is switched off.

Reread 20.4 Parsing Input into Typed Data if you chose differently.

Wrap-up · 7 of 8

Go further

MDN’s beginner guide walks through building a form, labels included: MDN: Your first form. Its page on validation lists every built-in attribute and what each one checks: MDN: Client-side form validation.

Wrap-up · 8 of 8

Reflection

Check each statement. If the answer is “not yet,” reread the linked subsection.

  • I can build a form whose inputs each have an id, a name, and a linked label. Reread
  • I can handle a form’s submit event and explain what happens without preventDefault. Reread
  • I can read form values with input.value and FormData, and narrow FormDataEntryValue | null to a string. Reread
  • I can write a parse function that returns a Result and rejects empty text before converting. Reread
  • I can validate every field of a form and return either typed data or all the messages at once. Reread
  • I can show each error next to its field with aria-live, aria-describedby and aria-invalid, and clear it once fixed. Reread
  • I can say what required, type="email", min and max check, and why my own validation must run too. Reread
  • I can update a result as the user types with the input event. Reread