Practice: Form Validation
Helpful error messages.
A good form tells you what's wrong before you send it, right next to the field that needs fixing. Let's validate a sign up form with JavaScript, and show friendly messages.

- Check before sending
- Messages next to fields
- Friendly errors
Validating on submit
Rules maps each field's name to a function that returns an error message, or an empty string if the value is fine. On submit, we check every field, and write its message into the small element after it. If there are no errors, we show a success message. We submitted with a short name, a bad email, and a good password.
<link rel="stylesheet" href="style.css">
<form id="f">
<input name="name" placeholder="Name"><small></small>
<input name="email" placeholder="Email"><small></small>
<input name="password" placeholder="Password"><small></small>
<button>Sign up</button>
</form>
<script>
const rules = {
name: v => v.length < 2 ? "Name is too short" : "",
email: v => /^\S+@\S+\.\S+$/.test(v) ? "" : "Enter a valid email",
password: v => v.length >= 8 ? "" : "Use 8 or more characters",
};
f.onsubmit = (e) => { e.preventDefault(); let ok = true;
for (const [name, check] of Object.entries(rules)) {
const msg = check(f[name].value); f[name].nextElementSibling.textContent = msg;
if (msg) ok = false; }
if (ok) f.replaceChildren("Welcome aboard!"); };
</script>Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#f7df1e;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"type": "input[name=name]", "text": "A"}, {"type": "input[name=email]", "text": "ana@mail"}, {"type": "input[name=password]", "text": "longenough1"}, {"click": "button"}]Front end and back end
Checking in the browser gives instant feedback, but it's only for convenience. Anyone can skip your JavaScript and send data straight to the server. So the server must always check the data again. Browsers also have built in checks, like the required attribute, and type equals email.
| key | value |
|---|---|
| rules object | one check per field |
| nextElementSibling | the message slot |
| Check again | on the server |
| required, type | built-in checks |
Summary
The form used a rules object, one submit handler, and messages next to each field. And remember, the server must always check again. Next, an expense tracker.
Key takeaways- Rules per field
- Show messages inline
- Server checks too