JavaScript lesson · 26 min
JavaScript Form Submit Handling
Handle a form submit event, prevent page reload, read FormData, and validate values.
What you will practice
- Listen for a submit event.
- Use preventDefault to keep control in JavaScript.
- Read form values with FormData and validate them.
What this means
A form submit event happens when a form is sent by a button, Enter key, or script.
By default, a browser form may navigate away or reload the page. `event.preventDefault()` stops that default behavior so JavaScript can handle the data first.
`FormData` reads named form fields and gives you their values without manually selecting every input.
If this is your first time seeing this
A form collects values. The submit handler decides what to do with them.
`preventDefault` keeps the browser from leaving the page before your code checks the data.
Mini glossary
- submit
- The event fired when a form is sent.
- preventDefault
- Stops the browser's normal built-in behavior for an event.
- FormData
- An API for reading named form fields.
Example from everyday life
Handling form submit is like a front desk checklist. Before sending a package onward, the desk checks the address, trims messy handwriting, and only accepts the package when the basic rules pass.
How it works step by step
- The example creates a form with email and password fields.
- The submit listener calls `preventDefault()` so the page does not reload.
- `new FormData(form)` reads the named inputs.
- The code trims the email, checks simple rules, and prints a friendly result.
Where you will use this
- A signup form checks email and password before sending a request.
- A search form reads the query and updates results without reloading.
- A settings form validates required fields before saving preferences.
Before you run the code
Client-side validation improves the user experience, but real applications must also validate on the server.
Always name form inputs when you plan to read them with FormData.
Common beginner mistakes
- Forgetting `name` attributes on inputs, so FormData cannot read useful values.
- Only validating in the browser and forgetting server validation in real apps.
- Not trimming text before checking it.
Run the code to see console output here.
Code runs locally in an isolated sandboxed browser frame with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Remove the `@` from the email and run the code.
- Make the password shorter than 8 characters.
- Add a `name="displayName"` input and validate that it is not empty.