Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 50 of 58

Forms and validation in plain JavaScript

Read form values in JavaScript, handle the submit event, use built-in HTML validation and add your own checks with clear error messages for users.

15 minThe DOM and eventsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonHandle a form submit event, read values with FormData, use the browser's built-in validation and show your own helpful error messages.

Forms are where users give your page information: a search, a sign-up, a message. After this lesson you will be able to handle a form in JavaScript, read its values, and check them, with good messages for the person using it.

The submit event

A form is submitted when the user clicks a submit button or presses Enter in a text field. Both trigger one event, submit, fired on the <form>. Listen for that rather than for a click on the button, so keyboard submissions are not missed.

By default, submitting reloads the page (or navigates to the form's action). When you handle the data yourself, stop that with event.preventDefault().

html
<form id="hello">
  <label>Your name <input id="who" name="who"></label>
  <button type="submit">Greet</button>
</form>
<p id="out"></p>
<script>
  document.getElementById("hello").addEventListener("submit", function (event) {
    event.preventDefault();
    const who = document.getElementById("who").value.trim();
    document.getElementById("out").textContent = who ? "Hello, " + who + "!" : "Please type a name.";
  });
</script>

Type a name and press Enter without touching the mouse: it works, because submit fired.

Reading values

For a single field, read input.value. It is always a string, even for type="number", so convert before calculating: Number(input.value).

For checkboxes use input.checked (true or false). For a group of radio buttons, query the checked one: form.querySelector("input[name=size]:checked"). For a <select>, select.value is the chosen option's value.

When a form has many fields, FormData collects everything by the name attributes:

html
<form id="order">
  <label>Item <input name="item" value="Tea"></label><br>
  <label>Quantity <input name="qty" type="number" value="2" min="1"></label><br>
  <label><input name="gift" type="checkbox"> Gift wrap</label><br>
  <button>Show order</button>
</form>
<pre id="out"></pre>
<script>
  document.getElementById("order").addEventListener("submit", function (event) {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const order = {
      item: data.get("item"),
      qty: Number(data.get("qty")),
      gift: data.has("gift")
    };
    document.getElementById("out").textContent = JSON.stringify(order, null, 2);
  });
</script>

Two details: a field is only included if it has a name, and an unchecked checkbox is absent from the data, which is why we use has. Object.fromEntries(data) turns all entries into a plain object when you need one.

Built-in validation

HTML already checks lots of things for you. Add attributes and the browser blocks submission and shows a message:

Attribute Checks
required the field is not empty
type="email", type="url" a plausible format
minlength, maxlength text length
min, max, step number or date range
pattern="[A-Za-z]+" text matches a regular expression

When validation fails, the submit event does not fire, so your handler only runs on valid data. You can ask yourself in code with form.checkValidity() or input.checkValidity(), and read input.validationMessage for the browser's wording.

Custom checks and messages

The built-in messages are generic, and some rules need logic, such as "the two passwords must match". Do the check yourself and show a message near the field, in text that tells the user how to fix it.

html
<form id="signup" novalidate>
  <label>Password <input id="pw" type="password" minlength="8"></label>
  <span id="pw-error" role="alert" style="color:#b91c1c"></span><br>
  <label>Repeat <input id="pw2" type="password"></label>
  <span id="pw2-error" role="alert" style="color:#b91c1c"></span><br>
  <button>Create account</button>
</form>
<p id="done"></p>
<script>
  const form = document.getElementById("signup");
  form.addEventListener("submit", function (event) {
    event.preventDefault();
    const pw = document.getElementById("pw");
    const pw2 = document.getElementById("pw2");
    const pwError = document.getElementById("pw-error");
    const pw2Error = document.getElementById("pw2-error");
    pwError.textContent = "";
    pw2Error.textContent = "";
    document.getElementById("done").textContent = "";
    let ok = true;

    if (pw.value.length < 8) {
      pwError.textContent = " Use at least 8 characters.";
      ok = false;
    }
    if (pw2.value !== pw.value) {
      pw2Error.textContent = " The passwords do not match.";
      ok = false;
    }
    if (ok) document.getElementById("done").textContent = "Looks good. Account would be created.";
  });
</script>

novalidate turns off the browser's own pop-ups so our messages are the only ones. You can also keep the browser checks and add yours on top with input.setCustomValidity("message"), which marks the field invalid until you call it again with an empty string.

Good error messages say what is wrong and how to fix it, appear next to the field, and are readable by assistive technology (that is the role of role="alert" above). Do not rely on colour alone.

Validation is not security

Everything above runs in the user's browser, so anyone can bypass it, by editing the page or by sending a request without using your page at all. Treat client-side validation as a convenience for honest users. Any server that receives the data must check it again. Never trust data just because your form "would not allow" it.

Giving feedback while the user types

You do not have to wait for the submit button. Listening to the input event lets you check a field as it changes, for example to show a character counter or to tell someone a username is too short. A good pattern is to validate on blur, when the user leaves a field, and again on input once an error is showing so that the message disappears as soon as the problem is fixed. Showing an error while someone is still typing their first character is irritating, so be gentle.

Disable the submit button only when there is a good reason, and say why. A greyed-out button with no explanation leaves people guessing. It is usually kinder to let them press it and then explain exactly what needs to change.

Move focus to the first invalid field after a failed submit, with input.focus(), so keyboard and screen reader users land where the problem is. Combined with clear text next to each field, this makes your form far easier to use, and that matters more than any clever validation rule.

Common mistakes

  • Forgetting preventDefault(). The page reloads and your result vanishes.
  • Listening to the button's click and missing Enter-key submissions.
  • Treating value as a number. "2" + "3" is "23". Convert first.
  • Missing name attributes, so FormData is empty for those fields.
  • Not trimming. Users add spaces; value.trim() avoids "empty" fields that contain spaces.
  • Checking .checked on a text input or .value on a checkbox, which is always "on" when ticked.
  • Using a button inside a form without type. It is a submit button by default; add type="button" for others.
  • Showing errors only in an alert() box. Put them next to the field.

Exercise

Build a contact form with name, email and message. Require all three, validate that the message has at least 20 characters, and show an inline error for each problem. When valid, collect the values with FormData and show them in a summary below the form. Check that pressing Enter in the name field submits the form.

Next: localStorage.

Key points

  • Listen for the submit event on the form, not for clicks on the button, so Enter key submissions are covered.
  • Call event.preventDefault() when you want to handle the form in JavaScript instead of reloading the page.
  • new FormData(form) collects the values by field name; input.value reads one field.
  • HTML attributes such as required, type, minlength and pattern give free validation, and checkValidity() reports the result.
  • Client-side validation helps users but is never a security measure; a server must validate again.

Check yourself

1. Why listen for submit on the form instead of click on the submit button?
2. What is the value of input.value for a number input in JavaScript?
3. What does new FormData(form).get("email") return?
4. Is checking an email with JavaScript in the browser enough to protect your server?
5. Which attribute stops a form submitting when a field is empty?

Free tools for this lesson