Web Fundamentals: Forms and Validation
The Form Element
Forms collect input from users. Every form has a method and an action. The action is the URL where the data goes, and the method is the HTTP verb, almost always GET or POST. Inside the form, input fields, text areas, selects, and buttons capture different kinds of data.
<form action="/signup" method="post">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
<label for="password">Password</label>
<input type="password" id="password" name="password" minlength="8" required>
<button type="submit">Create account</button>
</form>Each input needs a name attribute because the browser sends the name and value pair to the server. The label element is tied to an input through the for attribute, which improves accessibility and makes clicking the label focus the field.
Built-in Validation
Modern browsers validate without any JavaScript. The required attribute blocks empty fields. type email and type url check the format. minlength and maxlength bound text length. min and max bound numbers and dates. pattern checks a regular expression.
<input type="text" name="username" pattern="[a-z0-9_]{3,16}">This field only accepts lowercase letters, digits, and underscores, between 3 and 16 characters. Browser messages are automatic, and the form will not submit while a constraint fails.
JavaScript Validation for Nicer Feedback
For custom messages or inline hints, listen to the form submit event, check values in JavaScript, and prevent submission with preventDefault when something is wrong.
const form = document.getElementById("signup");
form.addEventListener("submit", (event) => {
const email = document.getElementById("email").value;
if (!email.includes("@")) {
event.preventDefault();
alert("Enter a valid email");
}
});Client-side checks make the app feel fast, but they never protect the server. Attackers can bypass the browser entirely, so the server must validate every field again. The client code is a convenience; the server check is the security boundary.
Key Points
- Every input needs a name so its value is submitted.
- HTML5 attributes such as required, type, and pattern validate for free.
- Labels bound with for improve accessibility and usability.
- Always validate on the server even when the client also checks.