Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT FORMS / CHAPTER 05 / Learn / LESSON 10
Project. We combine everything into a small signup: labels, reading fields, normalization, rules, aria messages, and success on submit.
Plan for the submit listener: 1. preventDefault(). 2. Clear old errors (text and aria-invalid). 3. Read and normalize: name.value.trim(), Number(age.value), terms.checked. 4. For every rule that breaks, put text into <p id="…-error"> and set aria-invalid="true" + aria-describedby. 5. If there are errors — a status with their count; otherwise "Welcome" (simulated success, no network).
A helper reduces repetition:
function fail(field, error, text) { error.textContent = text; field.setAttribute("aria-invalid", "true"); field.setAttribute("aria-describedby", error.id); }
IMPORTANT in the real world: client-side validation improves convenience but does NOT replace the server check. There is no server here — a real signup must validate again and never trust the browser.
Common mistake: errors that stay after a fix; one general message instead of one per field; a 0 or empty age being confused.
<form id="signup" novalidate><label for="name">Name</label><input id="name" name="name" type="text"><p id="name-error"></p><label for="email">Email</label><input id="email" name="email" type="email"><p id="email-error"></p><label for="age">Age</label><input id="age" name="age" type="number"><p id="age-error"></p><label><input id="terms" name="terms" type="checkbox"> I accept the terms</label><p id="terms-error"></p><button type="submit">Sign up</button></form><p id="status"></p>Combines labels, normalization, rules, aria, and simulated success in one submit listener.
Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›