submit, preventDefault, FormData & validation
Handle forms the right way
Lesson 8 of 20 · 12 min · Module 2: Respond to people
Forms are how people send you information. Handled well, they work with the Enter key, use the browser’s own validation, and never reload the page by accident.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Handle the submit event
- Read form values with FormData
- Let the browser validate before your code runs
The idea
Listen for the form’s submit event rather than a click on its button: it also fires when someone presses Enter, and only after the browser has checked attributes such as required and type="email". Call event.preventDefault() to stay on the page, read all fields with new FormData(form), and clear them with form.reset().
form.addEventListener('submit', event => {
event.preventDefault();
const data = new FormData(form);
console.log(data.get('email'));
});
01Submit, not click
A submit listener catches every way of sending a form: the button, the Enter key, and assistive technology. It also runs only when the built-in validation passes, so required fields and email formats are checked for free.
02FormData reads by name
new FormData(form) collects every named field. get returns one value, getAll returns several (for checkboxes with the same name), and Object.fromEntries(data) turns everything into an object.
const data = new FormData(form);
console.log(Object.fromEntries(data));{"name":"Ana","email":"[email protected]","topic":"CSS"}03Without preventDefault
The browser would send the form and load a new page, wiping out your message. preventDefault() keeps people on the page while your code handles the data, for example by sending it with fetch later in this course.
Your turn
submit on #signup. Prevent the default, read the fields with FormData, and show Thanks, Ana! We'll write to [email protected] about JavaScript. in #result (using the real name, email and chosen topic). Then reset the form. Invalid forms must not show a message.What the checks look for
- Submitting shows the thank-you message
- Pressing the button works too
- The form is cleared afterwards
- Invalid data shows no message
- The page stays put after submitting
Take this with you
Handle submit, prevent the reload, read FormData, reset.
Go a little further
Show your own error messages with input.setCustomValidity() for names shorter than two characters.