← JavaScript Essentials
DOM and browser interaction · 15 MIN

Forms and validation

Forms and validation

Listen for submit on the form, prevent navigation when handling it in JavaScript, read values from FormData and validate them. Show clear feedback and keep server-side validation for any data sent to a backend.

Try it yourself

Change the example, run it, and explain the result in your own words. Then create one variation of your own.

Key idea

Use the example as a starting point, not something to memorize. Practise, inspect the result and make small improvements.

Code example

const form = document.querySelector("form");
form.addEventListener("submit", event => {
  event.preventDefault();
  const data = new FormData(form);
  console.log(data.get("email"));
});