Project: Form Validation
This project builds the Fee Tracker's parent sign-up form: name, email, ZIP code, phone, password and confirmation. Good validation is a balance: catch mistakes early enough to be helpful, but not so early that people are scolded while still typing; show errors next to the field and announce them to screen readers; and never trust the browser alone (the server validates again). The design keeps every rule as a small pure function, so the same rules can run in the browser, on the server and in tests.
What You'll Build
- Fields with HTML validation attributes as the first layer.
- A table of pure validator functions, one per field, with clear messages.
- Errors appear when a field is left (blur) or on submit, and disappear as soon as the value is fixed.
- Accessible errors: linked with
aria-describedby, marked witharia-invalid, focus moved to the first error on submit. - A password strength meter and a "passwords match" check.
- A submit handler that disables the button while saving and never double-submits.
Step 1: HTML First
<form id="signup" novalidate>
<label for="name">Parent name</label>
<input id="name" name="name" autocomplete="name" required maxlength="80" aria-describedby="name-error">
<p id="name-error" class="error"></p>
<label for="email">Email</label>
<input id="email" name="email" type="email" autocomplete="email" required aria-describedby="email-error">
<p id="email-error" class="error"></p>
<label for="zip">ZIP code</label>
<input id="zip" name="zip" inputmode="numeric" autocomplete="postal-code" required aria-describedby="zip-error">
<p id="zip-error" class="error"></p>
<label for="password">Password (12+ characters)</label>
<input id="password" name="password" type="password" autocomplete="new-password" required minlength="12" aria-describedby="password-help password-error">
<p id="password-help">Strength: <span id="strength">empty</span></p>
<p id="password-error" class="error"></p>
<button>Create account</button>
</form>autocomplete values let browsers and password managers fill fields correctly; inputmode="numeric" shows a number keypad on phones without the quirks of type="number" (which would drop leading zeros in ZIP codes). novalidate turns off the browser's popups, because this form shows its own messages, but the attributes still document the rules.
Step 2: Pure Validators
Each validator takes the field's value (and all values, for cross-field rules) and returns an error message, or an empty string when the value is fine:
const validators = {
name: (v) => (v.trim().length === 0 ? "Enter your name." : v.trim().length > 80 ? "Use 80 characters or fewer." : ""),
email: (v) => (v.trim() === "" ? "Enter your email." : /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim()) ? "" : "Enter an email like name@example.com."),
zip: (v) => (/^\d{5}(-\d{4})?$/.test(v.trim()) ? "" : "Enter a 5-digit ZIP code."),
password: (v) => (v.length >= 12 ? "" : `Use at least 12 characters (${v.length} so far).`),
confirm: (v, all) => (v === all.password ? "" : "Passwords don't match."),
};
function validateAll(values) {
return Object.fromEntries(Object.entries(validators).map(([field, check]) => [field, check(values[field] ?? "", values)]));
}
console.log(validateAll({ name: "Srihitha Anamaneni", email: "srihitha@example", zip: "9410", password: "short", confirm: "shrt" }));
console.log(Object.values(validateAll({ name: "Navika", email: "navika@example.com", zip: "75201", password: "fee-tracker-2026", confirm: "fee-tracker-2026" })).every((e) => e === ""));{ name: '', email: 'Enter an email like name@example.com.', zip: 'Enter a 5-digit ZIP code.', password: 'Use at least 12 characters (5 so far).', confirm: 'Passwords don't match.' }
trueMessages say how to fix the problem ("Enter a 5-digit ZIP code"), not just that something is wrong ("Invalid input").
Step 3: When to Show Errors
| Moment | Behavior | Why |
|---|---|---|
| While typing a field for the first time | No error | Don't scold people mid-word |
When leaving a field (blur) | Show its error | They've finished, so feedback is useful |
| While typing in a field that already shows an error | Re-check on every input; clear as soon as it's valid | Immediate confirmation that the fix worked |
| On submit | Check everything; focus the first invalid field | Nothing gets past |
Track which fields the user has "touched" to implement this:
const touched = new Set();
const shouldShow = (field, event) => event === "submit" || event === "blur" || touched.has(field);
function onEvent(field, event) {
if (event === "blur" || event === "submit") touched.add(field);
return shouldShow(field, event);
}
console.log(onEvent("email", "input"), onEvent("email", "blur"), onEvent("email", "input"));false true trueStep 4: Showing Errors Accessibly
function showError(form, field, message) {
const input = form.elements[field];
const error = form.querySelector(`#${field}-error`);
error.textContent = message;
input.setAttribute("aria-invalid", String(message !== ""));
}aria-describedby (already in the HTML) makes screen readers read the error with the field's label; aria-invalid="true" announces the field as invalid. On submit, moving focus to the first invalid field takes keyboard and screen reader users straight to the problem.
Step 5: Password Strength
A simple, honest strength meter: length matters most, and variety helps:
function strength(pw) {
if (pw.length === 0) return "empty";
let score = pw.length >= 16 ? 2 : pw.length >= 12 ? 1 : 0;
score += [/[a-z]/, /[A-Z]/, /\d/, /[^\w\s]/].filter((re) => re.test(pw)).length >= 3 ? 1 : 0;
return ["weak", "fair", "good", "strong"][score];
}
for (const pw of ["", "password", "feetracker2026", "Fee-Tracker-2026!", "correct horse battery staple"]) {
console.log(JSON.stringify(pw).padEnd(31), strength(pw));
}"" empty
"password" weak
"feetracker2026" fair
"Fee-Tracker-2026!" strong
"correct horse battery staple" goodReal sites also check passwords against lists of known breached passwords (on the server). Never block pasting into password fields: password managers rely on it.
The Complete Form
The checker leaves the email field with a bad value (an error appears), fixes it (the error clears while typing), then submits with a short password (focus goes to it), and finally submits a valid form:
<form id="signup" novalidate>
<input id="name" name="name" aria-describedby="name-error"><p id="name-error"></p>
<input id="email" name="email" type="email" aria-describedby="email-error"><p id="email-error"></p>
<input id="zip" name="zip" inputmode="numeric" aria-describedby="zip-error"><p id="zip-error"></p>
<input id="password" name="password" type="password" aria-describedby="password-error"><p id="password-error"></p>
<input id="confirm" name="confirm" type="password" aria-describedby="confirm-error"><p id="confirm-error"></p>
<button id="submit">Create account</button>
</form>
<script type="module">
const validators = {
name: (v) => (v.trim() ? "" : "Enter your name."),
email: (v) => (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim()) ? "" : "Enter an email like name@example.com."),
zip: (v) => (/^\d{5}(-\d{4})?$/.test(v.trim()) ? "" : "Enter a 5-digit ZIP code."),
password: (v) => (v.length >= 12 ? "" : `Use at least 12 characters (${v.length} so far).`),
confirm: (v, all) => (v === all.password ? "" : "Passwords don't match."),
};
const form = document.querySelector("#signup");
const touched = new Set();
let saving = false;
const values = () => Object.fromEntries(new FormData(form));
function check(field, show) {
const message = validators[field](form.elements[field].value, values());
if (show) {
form.querySelector(`#${field}-error`).textContent = message;
form.elements[field].setAttribute("aria-invalid", String(message !== ""));
}
return message;
}
form.addEventListener("focusout", (e) => {
const field = e.target.name;
if (!(field in validators)) return;
touched.add(field);
const msg = check(field, true);
if (msg) console.log(`blur ${field}: ${msg}`);
});
form.addEventListener("input", (e) => {
const field = e.target.name;
if (touched.has(field) && check(field, true) === "") console.log(`fixed ${field}`);
});
form.addEventListener("submit", async (e) => {
e.preventDefault();
if (saving) return;
const errors = Object.keys(validators).filter((f) => check(f, true) !== "");
if (errors.length) {
form.elements[errors[0]].focus();
console.log(`submit blocked: ${errors.join(", ")}; focus on ${document.activeElement.id}`);
return;
}
saving = true;
form.querySelector("#submit").disabled = true;
await new Promise((r) => setTimeout(r, 50));
console.log(`account created for ${values().email}`);
});
</script>blur email: Enter an email like name@example.com.
blur zip: Enter a 5-digit ZIP code.
fixed email
fixed zip
blur password: Use at least 12 characters (5 so far).
submit blocked: password; focus on password
fixed password
fixed confirm
account created for navika@example.comExplanation: no error appeared while the email was first typed; it appeared when the checker moved on, and the empty ZIP field got its error the moment it was left too. Each error cleared the instant its value became valid ("fixed email", "fixed zip"), because touched fields are re-checked on every input. The first submit was blocked by the short password, with focus moved there; once the password and confirmation were fixed, the second submit succeeded, and the button was disabled during the (simulated) save, so a double click can't create two accounts.
Practice
Challenge: Add a US phone field validator that accepts (214) 555-0100, 214-555-0100 and 2145550100, and returns the normalized (214) 555-0100 form along with any error:
Show solution
function validatePhone(input) {
const digits = input.replace(/\D/g, "").replace(/^1(?=\d{10}$)/, "");
if (digits.length !== 10) return { error: "Enter a 10-digit US phone number.", value: input };
return { error: "", value: `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}` };
}
for (const p of ["(214) 555-0100", "214-555-0100", "+1 415 555 0199", "555-0100"]) console.log(validatePhone(p));{ error: '', value: '(214) 555-0100' }
{ error: '', value: '(214) 555-0100' }
{ error: '', value: '(415) 555-0199' }
{ error: 'Enter a 10-digit US phone number.', value: '555-0100' }Key Takeaways
| Piece | Technique |
|---|---|
| Rules | validators[field](value, allValues) |
| Timing | focusout to show, input to re-check touched fields |
| Errors | textContent in a linked <p>, aria-invalid |
| Submit | Validate all, focus the first error, disable while saving |
| Security | Server-side validation; passwords only over HTTPS, stored hashed |
Was this tutorial helpful?