JavaScript Forms

Read input values and validate forms.

✍️ 3 exercises + code challenge in this lesson

JavaScript can read and validate form data before it is sent.

  • Read a field with input.value (always a string).
  • Listen to the form's submit event and call event.preventDefault() to stop the page from reloading.
  • new FormData(form) collects every named field.
  • input.checkValidity() uses the HTML validation rules (required, type, pattern).

Key Takeaways: JavaScript Forms

Mastering JavaScript Forms helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Forms Code Example

JavaScript
<form id="signup">
  <input name="name" placeholder="Name" required><br><br>
  <input name="email" type="email" placeholder="Email" required><br><br>
  <input name="password" type="password" placeholder="Password (8+ chars)"><br><br>
  <button>Sign up</button>
</form>
<p id="msg"></p>

<script>
  document.getElementById("signup").addEventListener("submit", (e) => {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(e.target));
    const msg = document.getElementById("msg");

    if (data.password.length < 8) {
      msg.style.color = "#E34F26";
      msg.textContent = "Password must be at least 8 characters.";
      return;
    }
    msg.style.color = "#14B8A6";
    msg.textContent = `Welcome, ${data.name}! (${data.email})`;
  });
</script>
Free sign-in required · Google login available

JavaScript Forms Practice Exercises

Check what you learned in “JavaScript Forms”.

/ 3 solved
Fill in the blank

Stop the form from reloading the page.

form.addEventListener("submit", (e) => {
  e.();
});
✓ Correct! Not quite. Try again.
Multiple choice

What type is input.value always?

✓ Correct! Not quite. Try again.
Code challenge

Read the value of the input with id "name" and show it in #out as "Hello, <value>". (Run it on load.)

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services