Form Validation
Never trust user input! JavaScript allows you to validate emails, passwords, and other inputs instantly before sending them to a server.
Intercepting Submit
Listen for the submit event on the form, and use e.preventDefault() to stop the page from reloading.
const form = document.querySelector('#myForm');
const emailInput = document.querySelector('#email');
form.addEventListener('submit', (e) => {
e.preventDefault(); // Stop reload
if (!emailInput.value.includes('@')) {
alert("Please enter a valid email.");
return;
}
console.log("Form is valid! Sending data...");
});
Practice
Challenge 1: Add validation to ensure a password input is at least 8 characters long.