Forms & Validation

The Course
•
4 min read

A form is more than a button

A form groups fields and supports submission with Enter as well as a button click. Listen for the form’s submit event, not just the button’s click. Call event.preventDefault() to stop the default navigation so your JavaScript can handle this local demo.

A label connected to the input’s id tells people what to enter and makes the field easier to use. The input’s value is text—even when its type is number. Convert and validate it before updating state. Native constraints such as required and min help the browser guide users; JavaScript still needs rules for its own data.

Read the form’s HTML

MarkupJob
<form id="minutes-form">Group the input and submit button.
<label for="minutes">Name the input whose id is minutes. Clicking the label focuses that input.
<input id="minutes" type="number">Create an editable numeric field. Unlike a paragraph, input has no closing tag.
min="1" max="240" step="1" requiredDescribe the minimum, maximum, whole-number step, and requirement for a value.
<button type="submit">Submit the form that contains the button.

The input object’s .value property reads what the person typed as a string. In form.addEventListener("submit", event => { ... }), event is a parameter name: the browser supplies an event object when it calls the handler. .preventDefault() is a method of that object, not a function you must define.

The callback uses an arrow with a block because it has several instructions. Its job is to perform the submission steps, so it does not need to return a new value to the browser. The variables form, input, total, and feedback hold elements found by querySelector, not your numeric application data.

Trace a submission

  1. Read the text from the field.
  2. Validate and convert it.
  3. If invalid, show a specific message and leave state unchanged.
  4. Otherwise update state and display the new result.

The lab uses novalidate so you can observe every JavaScript validation branch. It is a deliberate teaching choice, not a requirement for real forms. The message has role=status so assistive technology can announce updates.

Press Run webpage to preview. Each run starts fresh. Edits are not saved automatically.

Try 25, blank text, 0, 240, 241, and 1.5. Submit once by clicking and once by pressing Enter. After a rejection, confirm the previous valid total remains. Change the success wording, run your edited page, and check again. Run webpage resets this demo’s state; typing in the source does not update the preview until you run it.

Test the conversion separately

The validation function can be tested without the DOM. This makes failures easier to locate: is the rule wrong, or did the event handler read the wrong field?

Test the conversion separately JavaScript
function parseMinutes(text) {
  if (text.trim() === "") {
    return null;
  }

  const value = Number(text);

  return Number.isInteger(value) && value >= 1 && value <= 240 ? value : null;
}

console.log(parseMinutes("25"));
console.log(parseMinutes(""));
console.log(parseMinutes("241"));
Check your prediction
25
null
null

The DOM handler should call this rule rather than inventing a slightly different one.

Exercise

Keep the last valid value

Simulate two submissions: valid 30 and invalid 0. Only valid values may replace current. Print current after each attempt.

Your working space JavaScript
let current = 10;
// Apply 30, then attempt 0.
Hint 1: the idea

Test the candidate before assigning to current.

Hint 2: a first step

A small loop can simulate the two submissions; keep current outside it.

Show one solution
let current = 10;

for (const candidate of [30, 0]) {
  if (Number.isInteger(candidate) && candidate >= 1 && candidate <= 240) {
    current = candidate;
  }

  console.log(current);
}
30
30

Now explain where the DOM version reads input, calls validation, and updates textContent.

Before the complete app

Can you explain why Enter works? Why does invalid input leave state alone? Add a reset button to your copy of the lab using type=button so it does not accidentally submit. Reset both the numeric state and visible message, then test another submission.

Was this article helpful?

Your response is saved on this device.