valueAsNumber Reads Numeric Input Values

Read number inputs with valueAsNumber instead of parsing .value by hand; empty or invalid fields yield NaN that Number.isNaN can catch before math.

TypescriptForm Validation

Code

typescriptsnippet
26 lines
const input = document.querySelector<HTMLInputElement>("#price");
const form = document.querySelector<HTMLFormElement>("#price-form");

if (!(input && form)) throw new Error("price form markup missing");

form.addEventListener("submit", (event) => {
  event.preventDefault();
  // number 输入框:valueAsNumber 直接给数值,空值或非法输入是 NaN
  const price = input.valueAsNumber;
  // 手动解析 .value 的对照路径:两者结果一致
  const parsed = Number(input.value);

  console.log(`valueAsNumber: ${price}`);
  console.log(`Number(value): ${parsed}`);
  console.log(`same: ${Object.is(price, parsed)}`);

  if (Number.isNaN(price)) {
    input.setAttribute("aria-invalid", "true");
    console.log("invalid: enter a number");
    return;
  }

  input.removeAttribute("aria-invalid");
  console.log(`total with vat: ${(price * 1.2).toFixed(2)}`);
});

Inside the code

The failure path is explicit — Error is raised when the guard condition holds.

Module-level bindings hold the data — input, form — with no function scope in between.

Points of care

  • Standard library end to end — paste it in and it runs.
  • This is browser-side code — document will not resolve in Node.

Applying it

Output lines are prefixed (valueAsNumber: $, Number(value): $, same: $), making each step’s effect easy to spot.

Statements that matter

if (!(input && form)) throw new Error("price form markup missing");

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
The code refuses to continue: `Error` is thrown while the state is still recoverable.
Does valueAsNumber Reads Numeric Input Values run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.