ILILCode
HomeJavaScriptThe browser

Forms: reading input and validating it

Read values, intercept submit with preventDefault, trim input and show feedback.

Lesson 12 of 23 in JavaScript10 min1 exercise

An <input> holds its current text in .value — always a string, even for type="number". Checkboxes use .checked. Read the value at the moment you need it, not once at startup.

A minimal form
<form id="signup">
  <input id="email" type="email" placeholder="you@example.com" />
  <button type="submit">Sign up</button>
</form>
<p id="msg" role="status"></p>

<script>
  const form = document.querySelector("#signup");
  const email = document.querySelector("#email");
  const msg = document.querySelector("#msg");

  form.addEventListener("submit", (event) => {
    event.preventDefault();          // stop the page reload
    const value = email.value.trim();

    if (!value) {
      msg.textContent = "Email required";
    } else if (!value.includes("@")) {
      msg.textContent = "Enter a valid email";
    } else {
      msg.textContent = `Thanks, ${value}`;
    }
  });
</script>

Without event.preventDefault() the browser navigates and your JavaScript never gets to respond. That is the single most common form bug.

Try it

Submit the form from code

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

Exercise

Validate an email signup

The form and the message paragraph are already built. Listen for submit and:

  1. 01call event.preventDefault()
  2. 02trim email.value
  3. 03set #msg to Email required when empty, Enter a valid email when it has no @, otherwise Thanks, <email>.
exercise.js
console · run your code or check the answer