Forms & Form Validation
How HTML input types, labels, and native validation attributes catch bad data before a single line of JavaScript runs.
Forms & Form Validation
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- The <input> type attribute changes both the keyboard a mobile device shows and the kind of value the browser expects, so picking the right type is free validation and better UX at once.
- A <label> tied to its input with a matching for and id isn't optional polish — it expands the clickable target and is how a screen reader announces what a field is for.
- Attributes like required, pattern, min, max, and maxlength let the browser reject bad input before any JavaScript or server code runs, for free.
- The Constraint Validation API (checkValidity, setCustomValidity, the :invalid CSS pseudo-class) lets you read and customize native validation instead of reimplementing it from scratch.
- Native validation is a first line of defense, not the whole defense — the server must always revalidate, because a client can be bypassed entirely.
The problem forms exist to solve
A web page that only displays information is a one-way street. Forms are how the street becomes two-way — how a user tells the application something, rather than the other way around. That sounds trivial until you consider what has to happen between a person typing “not-an-email” into an email field and that string never reaching your database: something has to look at the value, decide it’s malformed, and refuse to proceed. You could write that check yourself in JavaScript for every single field on every single form. HTML forms exist so that, for most common cases, you don’t have to.
Input types are the first layer
The <input> element’s type attribute is the cheapest validation you’ll ever write. type="email" tells the browser the value should look like an email address. type="number" restricts input to numeric values and gives desktop browsers up/down steppers. type="tel", type="url", type="date" each carry their own expectations. On mobile this isn’t just validation — it changes the on-screen keyboard. type="email" brings up a keyboard with @ and .com keys front and center; type="number" brings up a numeric pad. You get better UX and basic validation from a single attribute, before writing any logic at all.
This is worth pausing on, because it’s easy to default to type="text" for everything and handle the distinctions in JavaScript. That throws away a layer of validation and a chunk of mobile UX that costs nothing to keep.
Labels aren’t decoration
A <label> connected to its input via matching for and id attributes does two concrete things. First, clicking anywhere on the label text focuses or activates the associated input — genuinely useful for checkboxes and radio buttons, where the visual target is otherwise tiny. Second, and more important, a screen reader announces the label’s text when the input receives focus. An input with no connected label, or one where a placeholder is used as a stand-in for a label, is effectively unlabeled to someone using assistive technology — placeholder text disappears the moment the user starts typing, so it can’t serve as a persistent label.
<label for="email">Email address</label>
<input type="email" id="email" name="email" required>
Constraint attributes do the actual enforcing
Beyond type, a handful of attributes encode rules the browser enforces natively:
required— the field must have a value before the form submits.minlength/maxlength— bounds on text length.min/max— bounds on numeric or date values.pattern— a regular expression the value must match, for shapes none of the built-in types cover, like a specific product SKU format.step— the increment a numeric or date value must align to.
When any of these fail, the browser blocks submission and shows a built-in validation message, pointing at the offending field. No JavaScript required. This is the Constraint Validation mechanism doing exactly what its name says: enforcing constraints on form data as a built-in browser feature, not a library you installed.
The Constraint Validation API
Native validation messages are serviceable but generic, and sometimes you need more control — custom styling, custom wording, or validation logic HTML’s attributes can’t express (confirming two password fields match, for instance). The Constraint Validation API is the JavaScript layer that lets you work with native validation instead of discarding it.
Every form control has a validity property — a ValidityState object with booleans like valueMissing, patternMismatch, and tooShort telling you exactly which constraint failed. Calling element.checkValidity() runs the native checks and returns whether they passed. element.setCustomValidity("message") lets you inject your own validation failure — useful for rules HTML can’t express natively — and setCustomValidity("") clears it again. CSS pairs with this: the :invalid and :valid pseudo-classes let you style a field differently once it’s been interacted with, usually combined with :user-invalid or a :not(:placeholder-shown) guard so fields don’t show red before the user has even typed anything.
The API means you’re extending native validation rather than replacing it wholesale with a hand-rolled JavaScript validator that duplicates logic the browser already provides for free.
Submission, and the limit of all of this
A form’s action and method attributes determine where and how its data travels on submission — action is the URL, method is typically GET or POST. Modern apps often intercept submission with JavaScript (event.preventDefault() inside a submit listener) to send the data via fetch instead of a full page navigation, but the native validation still runs first and blocks that handler from firing if required fields are empty or malformed.
None of this replaces server-side validation. A browser enforces these constraints at the browser — anyone can send a raw HTTP request straight to your server with a tool like curl, skipping the HTML form, its required attributes, and its pattern checks entirely. Client-side validation is there for UX: instant, friendly feedback without a network round trip. The server must independently enforce every rule that actually matters, because the client can never be trusted to have run.
Check yourself
Why does setting type='email' on an input matter beyond just styling?
It tells the browser to validate the value as email-shaped before submission and, on mobile, swaps in a keyboard with @ and .com shortcuts — behavior you get for free just from the attribute.
What does a <label>'s for attribute actually connect, and what does it break if missing?
It connects the label's text to an input sharing the same id, which lets clicking the label focus the input and lets a screen reader read the label aloud when the input receives focus; without it, the input is effectively unlabeled for assistive tech.
What does the pattern attribute do that type alone can't?
It lets you specify a custom regular expression an input's value must match, covering shapes HTML's built-in types don't know about, like a specific product-code or postal-code format.
Why is client-side validation never sufficient on its own?
Anyone can submit a request directly to the server with a tool like curl, bypassing the browser's HTML entirely, so the server must independently validate and reject bad data regardless of what the form attempted to enforce.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.