Forms and Validation

Updated · 8 min read
mediumES2026javascriptformsvalidationformdataaccessibility

Forms are how people give data to a web page: payment amounts, names, dates, choices. JavaScript's job is to read the values, validate them, show helpful errors, and submit the result without reloading the page. Modern browsers do much of this already: HTML attributes like required, type="email" and min validate on their own, and the Constraint Validation API lets JavaScript use and customize that built-in checking. Start with HTML, then add JavaScript where HTML can't express the rule. (This is the "HTML first" approach.)

In One Minute

  • Listen for submit on the form (not click on the button), and call event.preventDefault() to handle it in JavaScript.
  • new FormData(form) reads every named field; Object.fromEntries(formData) turns it into a plain object.
  • HTML attributes validate for free: required, type="email", min, max, minlength, pattern, step.
  • form.checkValidity(), input.validity, input.setCustomValidity(message) and form.reportValidity() are the Constraint Validation API.
  • input fires on every change to a field's value; change fires when the change is committed (on blur, or immediately for checkboxes and selects).

Handling Submit

Listen to the form's submit event. It fires whether the person clicks the submit button or presses Enter in a field, which a button click listener would miss:

submit.html
<form id="payment">
  <label>Student <input name="student" value="Navika"></label>
  <label>Amount <input id="amount" name="amount" type="number"></label>
  <button>Record</button>
</form>
<script>
  document.querySelector("#payment").addEventListener("submit", (event) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    console.log(data.get("student"), data.get("amount"), typeof data.get("amount"));
  });
</script>
Output
Navika 120 string

Explanation: pressing Enter in the amount field submitted the form. preventDefault() stopped the page from reloading. FormData read the fields by their name attribute; every value is a string, even from a type="number" input, so convert before calculating.

Reading Form Data

CodeGives
new FormData(form)All named fields
formData.get("name")One value (string, or a File for file inputs), null if missing
formData.getAll("tags")Every value for a name (checkbox groups, multi-selects)
Object.fromEntries(formData)A plain object (last value wins for repeated names)
form.elements.amountThe field element itself
input.value, input.valueAsNumber, checkbox.checkedA field's live value
formdata.html
<form id="f">
  <input name="name" value="Advitha">
  <input name="grade" type="number" value="9">
  <label><input type="checkbox" name="extras" value="bus" checked> Bus</label>
  <label><input type="checkbox" name="extras" value="lunch" checked> Lunch</label>
  <label><input type="checkbox" name="extras" value="sports"> Sports</label>
  <select name="method"><option>card</option><option selected>check</option></select>
  <button id="b">Save</button>
</form>
<script>
  document.querySelector("#f").addEventListener("submit", (e) => {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    console.log(JSON.stringify(Object.fromEntries(data)));
    console.log(data.getAll("extras").join(", "));
    console.log(e.currentTarget.elements.grade.valueAsNumber + 1);
  });
</script>
Output
{"name":"Advitha","grade":"9","extras":"lunch","method":"check"}
bus, lunch
10

Unchecked boxes aren't included at all, and Object.fromEntries keeps only the last value for a repeated name ("lunch"); use getAll for groups. valueAsNumber reads a number input as a real number.

Built-In Validation

HTML attributes describe the rules, and the browser enforces them before submit fires:

AttributeRule
requiredMust not be empty
type="email", type="url"Must look like an email address or URL
type="number" with min, max, stepMust be a number in range, on a step
minlength, maxlengthText length limits
pattern="regex"Must match the regular expression (the whole value)
type="date" with min, maxDate range
builtin.html
<form id="f">
  <input id="email" name="email" type="email" required>
  <input id="amount" name="amount" type="number" min="1" max="5000" step="0.01" required>
  <button id="save">Save</button>
</form>
<script>
  const form = document.querySelector("#f");
  form.addEventListener("invalid", (e) => console.log("invalid:", e.target.name), true);
  form.addEventListener("submit", (e) => {
    e.preventDefault();
    console.log("submitted", new FormData(form).get("email"));
  });
</script>
Output
invalid: email
invalid: amount
submitted navika@example.com

Explanation: the first click found both fields empty. The browser fired an invalid event for each, showed its own message on the first one, and didn't fire submit. After the fields were filled in, the second click submitted. The invalid event doesn't bubble, so the listener uses the capture phase (the true argument).

The Constraint Validation API

JavaScript can read and extend the browser's validation:

MemberDescription
input.validityAn object of booleans: valueMissing, typeMismatch, rangeUnderflow, rangeOverflow, stepMismatch, tooShort, patternMismatch, customError, valid
input.validationMessageThe browser's message for the current problem
input.checkValidity() / form.checkValidity()Returns true or false (fires invalid events)
input.reportValidity() / form.reportValidity()Same, and shows the messages
input.setCustomValidity(message)Marks the field invalid with your message; "" marks it valid again
constraint.html
<input id="amount" type="number" min="1" max="5000" value="7500">
<input id="zip" pattern="\d{5}" value="7520">
<script>
  const amount = document.querySelector("#amount");
  const zip = document.querySelector("#zip");
  console.log(amount.validity.rangeOverflow, amount.validity.valid);
  console.log(zip.validity.patternMismatch);

  zip.setCustomValidity("Enter a 5-digit US ZIP code.");
  console.log(zip.validationMessage);
  zip.setCustomValidity("");
  zip.value = "75201";
  console.log(zip.checkValidity());
</script>
Output
true false
true
Enter a 5-digit US ZIP code.
true

setCustomValidity is how you add rules HTML can't express, such as "the payment can't exceed the balance", while still using the browser's error display. Remember to clear it with "" when the value becomes valid, or the field stays invalid forever.

Custom Error Messages

For full control over how errors look, turn off the browser's popups with the novalidate attribute on the form, keep the validation rules, and show messages in the page yourself:

custom-errors.html
<form id="f" novalidate>
  <label for="amount">Amount</label>
  <input id="amount" name="amount" type="number" min="1" max="450" required aria-describedby="amount-error">
  <p id="amount-error" role="alert"></p>
  <button id="save">Save</button>
</form>
<script>
  const form = document.querySelector("#f");
  const amount = form.elements.amount;
  const error = document.querySelector("#amount-error");

  function messageFor(input) {
    if (input.validity.valueMissing) return "Enter an amount.";
    if (input.validity.rangeOverflow) return `The balance is only $${input.max}.`;
    if (input.validity.rangeUnderflow) return "The amount must be at least $1.";
    return "";
  }

  form.addEventListener("submit", (e) => {
    e.preventDefault();
    error.textContent = messageFor(amount);
    amount.setAttribute("aria-invalid", String(!amount.validity.valid));
    console.log(amount.validity.valid ? `Saved $${amount.value}` : `Error: ${error.textContent}`);
  });
</script>
Output
Error: Enter an amount.
Error: The balance is only $450.
Saved $120

The error paragraph is linked to the field with aria-describedby and announced by screen readers through role="alert"; aria-invalid marks the field's state for assistive technology.

input and change Events

EventFires
inputOn every change of value: each keystroke, paste, autocomplete, voice input
changeWhen a change is committed: on blur for text fields, immediately for checkboxes, radios and selects
input-change.html
<input id="name"> <input id="other">
<p id="preview"></p>
<script>
  const name = document.querySelector("#name");
  name.addEventListener("input", () => {
    document.querySelector("#preview").textContent = `Receipt for ${name.value}`;
  });
  name.addEventListener("change", () => console.log("change:", name.value, "|", document.querySelector("#preview").textContent));
</script>
Output
change: Navika | Receipt for Navika

Use input for live previews and clearing errors, and change for "save this field" actions.

In Practice

The Fee Tracker's payment form combines it all: HTML rules, one custom rule (the amount can't exceed the student's balance), messages on submit and cleared on input, and the data handed to a function as a typed object:

payment-form.html
<form id="pay" novalidate data-balance="450">
  <select name="student"><option>Navika</option><option>Srihitha</option></select>
  <input id="amount" name="amount" type="number" min="1" step="0.01" required>
  <span id="err" role="alert"></span>
  <button id="save">Record payment</button>
</form>
<script>
  const form = document.querySelector("#pay");
  const amount = form.elements.amount;
  const err = document.querySelector("#err");

  function validate() {
    const balance = Number(form.dataset.balance);
    amount.setCustomValidity(amount.valueAsNumber > balance ? `Only $${balance} is due.` : "");
    err.textContent = amount.validity.valid ? "" : amount.validationMessage;
    return amount.validity.valid;
  }

  amount.addEventListener("input", () => { if (err.textContent) validate(); });
  form.addEventListener("submit", (e) => {
    e.preventDefault();
    if (!validate()) return console.log("Blocked:", err.textContent);
    const { student, amount: value } = Object.fromEntries(new FormData(form));
    console.log(`Recorded $${Number(value).toFixed(2)} for ${student}`);
  });
</script>
Output
Blocked: Only $450 is due.
Recorded $200.00 for Navika

Common Mistakes

Listening to the button's click instead of the form's submit. Enter-key submissions are missed. Use submit.

Forgetting preventDefault(). The page reloads and your JavaScript never finishes.

Fields without name. FormData skips them.

Doing math on form values without converting. They are strings: use Number(...) or valueAsNumber.

Trusting client-side validation. Always validate on the server too.

Practice

Challenge: Build a form with a required email and a ZIP code that must be 5 digits. On submit, log either OK with both values or the name of the first invalid field.

Show solution
signup.html
<form id="f" novalidate>
  <input id="email" name="email" type="email" required>
  <input id="zip" name="zip" pattern="\d{5}" required>
  <button id="go">Sign up</button>
</form>
<script>
  document.querySelector("#f").addEventListener("submit", (e) => {
    e.preventDefault();
    const form = e.currentTarget;
    const firstInvalid = form.querySelector(":invalid");
    if (firstInvalid) return console.log("Invalid:", firstInvalid.name);
    const { email, zip } = Object.fromEntries(new FormData(form));
    console.log("OK", email, zip);
  });
</script>
Output
Invalid: zip
OK srihitha@example.com 94103

Quick check: Forms

3 questions
1Which event should you listen to for form submission?
2What type is new FormData(form).get("amount") for a number input?
3What does input.setCustomValidity("") do?

Key Takeaways

TaskCode
Handle submitform.addEventListener("submit", (e) => { e.preventDefault(); ... })
Read all fieldsObject.fromEntries(new FormData(form))
Is the form valid?form.checkValidity()
Custom ruleinput.setCustomValidity("message") / ("")
Live previewinput.addEventListener("input", ...)

Was this tutorial helpful?

Lesson 76 of 139