Good validation catches mistakes early and tells people how to fix them.
Direct answer
Add a submit event listener to the form, check the values, show a clear message for each problem and call event.preventDefault() if the form is invalid. Use HTML attributes like required and type="email" for simple checks. Always validate again on the server.
Example
<form id="signup" novalidate>
<input id="email" type="email" required>
<p id="error" role="alert"></p>
<button>Sign up</button>
</form>
const form = document.querySelector("#signup");
const email = document.querySelector("#email");
const error = document.querySelector("#error");
form.addEventListener("submit", (event) => {
if (!email.value.includes("@")) {
event.preventDefault();
error.textContent = "Please enter a valid email.";
} else {
error.textContent = "";
}
});
Tips
- Say what is wrong and how to fix it.
- Do not clear what the user typed.
- Use
aria-liveorrole="alert"for accessibility. - Validate on the server too.
Where Teyro fits
Teyro's Interactive Web Pages with JavaScript course turns this into short lessons you can play in a few minutes a day. It has 37 lessons, and you can start free.
The bottom line
Validate early for friendliness and again on the server for safety. See a full example.


