Module 7: DOM and Browser APIs
Forms, Input, and Validation
Read form values, validate input, and present useful errors to users.
Forms collect user input. Listen to the form's submit event rather than only the button's click, because users may submit with the keyboard. If the browser should not navigate away, call event.preventDefault() after you have deliberately handled submission.
const form = document.querySelector("#signup-form");
form?.addEventListener("submit", (event) => {
event.preventDefault();
const formData = new FormData(form);
const email = String(formData.get("email") ?? "").trim();
if (!email) {
console.error("Email is required.");
return;
}
console.log("Ready to submit", email);
});
Built-in constraints#
HTML attributes such as required, min, max, minlength, and type="email" provide useful client-side validation. JavaScript can add application-specific checks. However, browser validation can be bypassed, so a server must validate data too when it receives or stores it.
Show errors accessibly#
Tell users what field needs attention and how to fix it. Associate labels with controls, connect error text using aria-describedby when appropriate, and do not rely only on a red border or colour. Keep focus and keyboard behaviour predictable after failed submission.
Never trust client-side checks alone#
Client validation improves usability; it is not authorization or security. Validate and authorize again on the server, and encode output safely when displaying submitted content.
Practice#
Build a form with name and email fields. Use browser constraints plus JavaScript to normalize the input and show an understandable validation message.