ProgramGuru

Handling HTML Forms

Handling HTML Forms — why it matters

HTML forms collect input; TypeScript can help shape the parsed values, but it cannot guarantee user-entered strings are valid. A submit event is often intercepted with preventDefault to perform custom validation. Check field presence, then convert and validate strings before creating typed application data.

What you’ll learn

  • Explain handling html forms and the problem it solves.
  • Identify the relevant compile-time checks and runtime responsibilities.
  • Run the example, predict its output, and try a realistic modification.

Understand the mechanism

Number converts the input string at runtime. The guard rejects a blank name and invalid age, and successful parsing returns a runtime object conforming to Signup.

Casting an input string to number with as number does not convert the underlying JavaScript value.

Follow the concept flow

Handling HTML Forms — concept flowString inputs → Parse and validate → Typed form dataHandling HTML Forms1String inputs2Parse and validate3Typed form dataBrowser code needs browser APIs; Node code needs Node.js APIs.
Follow the responsibilities from input to checked result.

Run the primary TypeScript example

Save as handling-html-forms.ts. The following program passed strict TypeScript compilation, and the displayed output was captured by executing its emitted JavaScript with Node.js 22.16.0.

TypeScript source

type Signup = { name: string; age: number };
function parseSignup(name: string, ageText: string): Signup | null {
  const age = Number(ageText);
  if (!name.trim() || !Number.isInteger(age) || age < 1) return null;
  return { name: name.trim(), age };
}
console.log(parseSignup("Asha", "19"));
console.log(parseSignup("", "19"));

Verified output

{ name: 'Asha', age: 19 }
null

Compile: npx tsc --strict --target es2022 --module commonjs handling-html-forms.ts; run: node handling-html-forms.js. For Node.js API examples, install @types/node first. For browser projects, use the browser-specific instructions below.

The example runs in Node.js 22.16.0; if it reads runtime environment details, your displayed values may differ.

Trace the result

Number converts the input string at runtime. The guard rejects a blank name and invalid age, and successful parsing returns a runtime object conforming to Signup.

Predict what changes if you alter one input. Then run the code to compare your reasoning with the real output.

Build the real browser interaction

Real browser lab: This TypeScript targets actual DOM APIs and was successfully type-checked against the DOM library. It requires a browser; its runtime interaction was not simulated in Node.js. Save the two files together, compile the TypeScript, and serve this folder through a local HTTP server such as python3 -m http.server 8000 (especially important for modules and workers).

index.html

<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>TypeScript browser lab</title></head><body>
<form id="signup"><label>Age <input id="age" type="number" required></label><button>Save</button></form><output id="result"></output>
<script type="module" src="./app.js"></script>
</body></html>

app.ts

const form = document.querySelector<HTMLFormElement>("#signup");
const input = document.querySelector<HTMLInputElement>("#age");
const output = document.querySelector<HTMLOutputElement>("#result");
form?.addEventListener("submit", (event: SubmitEvent) => {
  event.preventDefault();
  const age = Number(input?.value);
  if (output) output.textContent = Number.isInteger(age) && age >= 1 ? `Age: ${age}` : "Enter a valid age";
});

Compile: npx tsc --strict --target es2022 --module es2022 --lib es2022,dom app.ts. For the worker example also compile worker.ts with --lib es2022,webworker. Then open the served HTML page in a browser to interact with it.

Common mistake and correction

Casting an input string to number with as number does not convert the underlying JavaScript value.

Identify whether the failure is a type-checking issue, a configuration issue, or a runtime behavior issue before choosing a fix.

Practice the concept

Add an email field and require an @ symbol before accepting the form. Display errors next to the field.

Write down your expected result first. For configuration examples, compare compiler output and diagnostics; for test examples, make the assertion fail deliberately to verify that the tool reports it.

Check your understanding

Which statement best describes the role of TypeScript and the actual runtime for this lesson?
Choose one answer. You can try again.

Answer and explanation

The described check or API works only within its stated environment and still needs the corresponding runtime behavior.

Number converts the input string at runtime. The guard rejects a blank name and invalid age, and successful parsing returns a runtime object conforming to Signup.

What to remember

HTML forms collect input; TypeScript can help shape the parsed values, but it cannot guarantee user-entered strings are valid.

Run the primary example, then complete the practice task or environment-specific lab.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Creating and Updating DOM Elements →