Form Controls Expose valueAsNumber And validity

Every control posts as a string, but number and range inputs expose valueAsNumber, checkboxes carry a value attribute, and validity maps failed rules.

JavascriptForm Validation

Code

javascriptsnippet
27 lines
// Every form control posts as a string; the quirks live in the checkbox and the number input.
const form = document.createElement("form");
form.innerHTML = `
  <input name="age" type="number" value="17">
  <input name="score" type="range" min="0" max="100" value="80">
  <input name="agree" type="checkbox" checked>
  <input name="coupon" type="checkbox" value="SAVE10">
  <select name="plan"><option selected>free</option><option>pro</option></select>
`;
document.body.append(form);

// checkbox: its value attribute when checked, "on" when unset, absent when unchecked
console.log("agree value:", form.elements.agree.value, "| coupon:", form.elements.coupon.value, form.elements.coupon.checked);

// number and range inputs expose valueAsNumber alongside the string value
console.log("age:", JSON.stringify(form.elements.age.value), form.elements.age.valueAsNumber);
console.log("score asNumber:", form.elements.score.valueAsNumber);

// willValidate + checkValidity expose the built-in constraint set
for (const el of form.elements) {
  console.log(el.name, el.type, "valid:", el.willValidate ? el.checkValidity() : "n/a");
}

// FormData collapses it all back to strings
const data = new FormData(form);
console.log("formdata:", [...data.entries()].map(([k, v]) => k + "=" + v).join(" | "));
form.remove();

How the snippet works

The only loop is for (const el of form.elements), visiting each control once.

Two bindings anchor the demo: form, built from an inline template, and data, which collects the results.

Caveats

  • Nothing to install: the snippet stays inside the standard library.
  • document.createElement implies a DOM; without one there is no form to build and inspect.

Applying it

The file announces its steps in the output: agree value:, age:, score asNumber:.

Statements that matter

<select name="plan"><option selected>free</option><option>pro</option></select>
`;
const form = document.createElement("form");
const data = new FormData(form);

Interactive Tools for This Topic

FAQ

Does Form Controls Expose valueAsNumber And validity 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.