Forms that help people succeed
Read form input, validate it and report errors accessibly.
- Read an input value on submit
- Use preventDefault for a client-side form flow
- Show a clear error or success status
HTML gives a form labeled controls and native validation. CSS can highlight its state. JavaScript handles the submit event, reads the value, and updates feedback. Begin with <label>, an appropriate input type and native constraints. JavaScript checks can improve the experience, but a server must validate data again before trusting it.
1<form id="signup">
2 <label for="email">Email address</label>
3 <input id="email" name="email" type="email" required>
4 <button type="submit">Join</button>
5 <p id="feedback" role="status"></p>
6</form>
7<script src="signup.js" defer></script>1const form = document.querySelector("#signup");
2const feedback = document.querySelector("#feedback");
3form.addEventListener("submit", (event) => {
4 event.preventDefault();
5 const email = form.elements.namedItem("email").value.trim();
6 feedback.textContent = email ? "Thanks for joining!" : "Enter an email address.";
7});An application can use role="status" for nonurgent updates, so assistive technology can announce them without moving focus. Keep messages specific. If the server rejects a form, show that error near the field and allow correction. See MDN forms and W3C status messages.
Key takeaways
Use semantic labels, input types and native constraints first.
Handle submit, prevent default when staying on the page, and give specific feedback.
A server must validate input again.
Lesson quiz
2 questions · pass with 2 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write JavaScript
Write the program, run it against the test cases, and use the feedback to build your JavaScript skills.
Give useful form feedback
The starter creates a form in the isolated exercise page. On submit, prevent the default action, trim the input, and put Enter a name in the status paragraph if it is blank, otherwise Welcome, NAME!. The test submits the form and prints the status text.
- Name
- Blank
JavaScript runs in a sandboxed browser frame with a 1.5 second time limit. Input is available as the string variable input.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…