JavaScript in the page · Lesson 32 of 45
Forms and validation
Read form data, validate it, and show clear errors.
8 minutes2 games
Listen for submit on the form itself (not the button's click) so it also works when someone presses Enter. Read the data with new FormData(form).
HTML
<form id="signup" novalidate>
<p><label>Email <input name="email" type="email"></label></p>
<p><label>Password <input name="password" type="password"></label></p>
<p id="error" style="color: crimson"></p>
<button>Sign up</button>
</form>
<script>
const form = document.querySelector("#signup")
const error = document.querySelector("#error")
form.addEventListener("submit", (e) => {
e.preventDefault()
const data = Object.fromEntries(new FormData(form))
if (!data.email.includes("@")) return (error.textContent = "Enter a valid email")
if (data.password.length < 8) return (error.textContent = "Password needs 8+ characters")
error.textContent = ""
console.log("Sending", data)
})
</script>Try submitting it empty, then with a bad email, then correctly.
Complete the code
Stop the form from reloading the page.
form.addEventListener("submit", (e) => { e.() })
Exercise
Write isValidPassword(p) returning true if it's 8+ characters and contains a digit. Print isValidPassword("secret12").
Expected output: true
JavaScript
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.