Forms & Validation with JavaScript
Handling a form submit
form.addEventListener("submit", (e) => {
e.preventDefault(); // stop the page reload
const data = Object.fromEntries(new FormData(form));
// data = { email: "...", password: "..." }
});
FormData collects every field that has a name.
Validation in layers
- HTML attributes:
required,type="email",minlength,pattern. Free and accessible. - JavaScript for custom rules (passwords match, a username is available) and friendly messages:
input.setCustomValidity("Passwords don't match"), thenform.reportValidity().- Or show your own error text under the field.
- Server validation: always required, because the browser can be bypassed.
Good form UX
- Validate on
blurorsubmit, not on every keystroke, which is annoying. - Put error messages next to the field, in plain language: "Email must include @".
- Connect errors for screen readers with
aria-describedby. - Disable the submit button while sending, to prevent double submits.
- Keep what the user typed if something fails.
Example
<form id="signup" novalidate>
<label>Email<br /><input name="email" type="email" required /></label><br />
<label>Password<br /><input name="password" type="password" minlength="6" required /></label><br />
<label>Confirm<br /><input name="confirm" type="password" required /></label><br />
<p id="error" style="color: crimson"></p>
<button>Create account</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 (!form.checkValidity()) {
error.textContent = "Please enter a valid email and a 6+ character password.";
} else if (data.password !== data.confirm) {
error.textContent = "Passwords don't match.";
} else {
error.textContent = "";
alert("Welcome, " + data.email + "!");
form.reset();
}
});
</script>