Forms: Reading Input and Validating
Get data out of a form, check it before trusting it, and give the user clear feedback β both browser-native and JavaScript-side.
Forms are how your site listens. You know the HTML (Module 2) and events (last lesson) β now you read what the user typed and check it.
Reading values
const emailField = document.querySelector("#email");
emailField.value; // the current text β a string, always
.value works on inputs, textareas, and selects. It is always a string:
"25" is not a number β convert with Number(...) when you do math.
Two layers of validation
Layer 1 β the browser (free): with
<input type="email" required minlength="3">, the browser refuses to submit
invalid data and shows a message. Always start here.
Layer 2 β your JavaScript: the browser can't know your business rules ("name taken", "username must not contain spaces"). Handle the submit and check yourself:
const form = document.querySelector("#signup");
const errorBox = document.querySelector("#error");
form.addEventListener("submit", (event) => {
event.preventDefault();
const username = document.querySelector("#username").value.trim();
if (username.length < 3) {
errorBox.textContent = "Username must be at least 3 characters.";
return; // stop β don't accept the bad input
}
errorBox.textContent = ""; // clear old errors
console.log("Welcome, " + username);
});
Feedback that includes everyone
- Show errors in text on the page (color alone fails ~8% of men β colorblind users can't see "the red border").
- Put the message near the field it belongs to.
.trim()before checking: " " is not a real name even though it is not empty.
The pattern, generalized
- Intercept submit β
preventDefault() - Read + normalize values
- Check each rule; on first failure, show a message and stop
- All good β do the real work (save, send, render)
This read β validate β feedback loop is unchanged in every framework.
What you learned
.valuereads fields; it is always a string (Number()to convert)- Validate in layers: HTML attributes first, JavaScript for your rules
- Show errors as text near the field; never color alone
- Intercept, read, check, feedback β in that order
Next: remembering data between visits β storage.