Sub topic 3
Built-in Validation and Form Data
Assume basic HTML, browser developer tools, and JavaScript syntax. Native validation handles common rules before submission. JavaScript adds custom rules and can read the submitted controls.
Built-in validation with attributes
Use attributes such as required, minlength, min, max, and pattern. The browser blocks submission when a value violates a constraint.
<form id="profile" action="/profile" method="post"
enctype="multipart/form-data">
<label for="username">Username</label>
<input id="username" name="username" required minlength="3"
autocomplete="username" aria-describedby="username-error">
<p id="username-error" class="error"></p>
<fieldset>
<legend>Contact preference</legend>
<label><input type="radio" name="contact" value="email" required> Email</label>
<label><input type="radio" name="contact" value="phone"> Phone</label>
</fieldset>
<label for="avatar">Profile photo</label>
<input id="avatar" name="avatar" type="file" accept="image/*">
<button type="submit">Save</button>
</form>The name attribute identifies submitted data. A file upload also needs multipart/form-data, set with enctype.
Grouping, hints, and styling
fieldset groups related controls, while legend names the group. autocomplete tells the browser what kind of value it may fill, such as email, postal-code, or new-password.
Use :valid and :invalid carefully. Styling every empty optional field as invalid can confuse users, so add an error style after interaction when possible.
input:invalid {
border: 2px solid #b00020;
}
input:valid {
border: 2px solid #287a3e;
}
.error {
color: #b00020;
}JavaScript and custom validation
The submit event runs after built-in validation passes. FormData collects successful controls, including checked choices and selected files.
const form = document.querySelector("#profile");
const username = form.elements.username;
const error = document.querySelector("#username-error");
form.addEventListener("submit", (event) => {
event.preventDefault();
const data = new FormData(form);
console.log(data.get("username"));
});
username.addEventListener("input", () => {
const message = username.value.includes(" ")
? "Do not use spaces."
: "";
username.setCustomValidity(message);
error.textContent = message;
});setCustomValidity("") clears a custom error. Otherwise, the control remains invalid. Connect visible messages with aria-describedby, and give dynamic messages an appropriate announcement strategy such as role="alert".
> callout note > Always validate again on the server. Browser validation improves the interface, but it is not a security boundary.
Exercise
Why does an unchecked checkbox usually not appear in FormData?
Show answer
Only successful controls are submitted, and an unchecked checkbox is not successful.