30 min·intermediate

Lesson 5

Forms & validation

Build a practical mental model for forms & validation and use it in working JavaScript.

By the end, you will be able to…

  • Explain forms & validation in your own words
  • Use forms & validation in a small program
  • Recognize and debug a common failure mode

Build the mental model

Form submission reloads the page by default, so preventDefault() is almost always the first line of a submit handler. Validation should run before you trust or send any user-entered value.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: Prevents the page reload and validates before submitting

Why this matters

Client-side validation catches obvious mistakes instantly, improving the experience, even though the server must always re-validate for security.

Real-world example

Every signup form rejecting an invalid email before it ever reaches a server is this exact pattern.

Common mistakes

  • Forgetting event.preventDefault(), causing an unwanted full-page reload
  • Trusting client-side validation alone and skipping server-side checks
  • Validating only on submit instead of giving earlier, incremental feedback

Try it yourself

Challenge

Write isValidEmail(value) with a simple but real check (contains @ and a dot after it).

Practice

Knowledge check

Why call event.preventDefault() in a form's submit handler?

Summary

Call preventDefault() on submit, validate before trusting input, and never skip server-side validation too.