[FEE-103] Forms & Validation
INFO
HTML forms are the web's primary mechanism for collecting user input. The platform provides declarative validation, accessible labeling, and structured submission -- all before a single line of JavaScript runs. Understanding native form capabilities is essential because every framework-level form abstraction ultimately renders to these primitives.
Context
The <form> element has been part of HTML since the beginning. It defines a region of the page that collects user input and submits it to a server. Unlike most HTML elements, forms are interactive by default -- they accept input, validate it, and trigger navigation, all with zero JavaScript.
HTML provides a rich vocabulary of form controls:
| Element | Purpose |
|---|---|
<form> | Container that groups controls and defines submission behavior |
<input> | The most versatile control -- 22+ types (text, email, number, date, checkbox, radio, file, range, color, etc.) |
<textarea> | Multi-line text input |
<select> + <option> | Dropdown selection list |
<datalist> + <option> | Autocomplete suggestion list bound to an <input> via the list attribute |
<output> | Result of a calculation or user action (e.g., live total) |
<button> | Submit, reset, or generic button (prefer over <input type="submit">) |
<fieldset> + <legend> | Groups related controls with a caption |
<label> | Accessible name for a form control |
<progress> | Progress indicator |
<meter> | Scalar measurement within a known range |
Input types
Each type value changes the control's behavior, mobile keyboard, and built-in validation:
| Type | Keyboard | Built-in validation |
|---|---|---|
text | Standard | None (unless pattern is set) |
email | Email layout (@ key) | Must match email format |
url | URL layout | Must match URL format |
tel | Numeric dialpad | None (patterns vary by country) |
number | Numeric | Must be a number within min/max/step |
date | Date picker | Must be a valid date |
search | Standard + clear button | None |
password | Obscured input | None (use minlength/pattern) |
file | File picker | accept filters file types |
checkbox | Toggle | required means must be checked |
radio | Single-select within group | required on one means group must have selection |
range | Slider | Constrained to min/max/step |
color | Color picker | Must be a valid hex color |
Form submission attributes
The <form> element controls how data is sent:
action-- URL to submit to. Defaults to the current page URL.method--GET(data in URL query string) orPOST(data in request body).dialogcloses a<dialog>parent.enctype-- Encoding forPOST:application/x-www-form-urlencoded(default),multipart/form-data(required for file uploads),text/plain.novalidate-- Disables native validation on submission.
Individual submit buttons can override these with formaction, formmethod, formenctype, and formnovalidate:
<form action="/save" method="POST">
<!-- Fields here -->
<button type="submit">Save Draft</button>
<button type="submit" formaction="/publish" formmethod="POST">Publish</button>
</form>Scenario
You are building a checkout form that collects shipping address, payment details, and a delivery preference. The form submits with missing required fields and accepts obviously invalid postcodes because validation lives only in the submit handler — which the user bypasses by pressing Enter in a text field. HTML's built-in form validation — required, pattern, type="email", minlength — runs before the submit event fires, works without JavaScript, and surfaces native browser error UI with no additional code.
Design Thinking
Why HTML has native validation
HTML validation is declarative -- you describe constraints in markup, and the browser enforces them. This design has three advantages:
- Progressive enhancement. Forms work without JavaScript. If JS fails to load, native validation still prevents invalid submissions.
- Accessibility built in. Browsers announce validation errors to screen readers. The
:invalidand:user-invalidpseudo-classes enable visual feedback without JS state management. - Less code to maintain. A
requiredattribute replaces a JavaScript event listener, a state variable, conditional rendering of an error message, and an ARIA attribute. Native validation is a single source of truth.
The limitation: native validation UI is not customizable. The browser's error tooltip cannot be styled, its text varies across browsers, and its positioning is fixed. This tension drives frameworks to reimplement validation in JavaScript.
The framework forms landscape
Modern frameworks take different approaches to form handling, each balancing DX, progressive enhancement, and accessibility:
React: controlled vs. uncontrolled. Controlled components bind every input to React state via value + onChange, giving full control but requiring more code. Uncontrolled components use ref and let the DOM own the state -- closer to native forms. React 19+ introduced Server Actions with the action prop on <form>, allowing server-side form processing with progressive enhancement: forms work as standard HTML submissions when JS is unavailable.
Vue: v-model. Vue's v-model directive provides two-way data binding between form controls and component state. It handles the value/event wiring automatically for <input>, <textarea>, and <select>. Validation is typically handled by libraries like VeeValidate or FormKit.
SvelteKit: form actions. SvelteKit's form actions are the strongest progressive enhancement story. Forms submit as standard HTTP POST requests. Server-side actions functions process the submission. The use:enhance directive progressively upgrades to AJAX when JS is available -- no page reload, but the same server action handles both cases. This means forms work without JavaScript by design.
Remix / React Router: loader + action. Similar to SvelteKit, Remix uses server-side action functions that process standard form submissions. The <Form> component upgrades to fetch-based submission with JS. Progressive enhancement is a core design principle.
Conform + Zod. Conform is a form validation library designed for progressive enhancement with React Server Actions, Remix, and Next.js. It pairs with Zod schemas to define validation rules once and apply them on both client and server. This "validate once, run everywhere" approach eliminates the common mistake of divergent client/server validation.
The tension: native vs. framework validation
Native HTML validation is accessible and requires no JavaScript, but:
- Error messages cannot be styled or positioned
- Complex rules (cross-field validation, async checks) are not expressible
- Error UX varies across browsers
Framework validation is flexible but must recreate what the browser provides for free:
- Error messages must be wired to
aria-describedbyor live regions - Focus must be managed (move focus to the first invalid field)
- Submission prevention must be reimplemented
- Screen reader announcements must be explicitly coded
The best approach combines both: use native attributes (required, type="email", pattern) for baseline validation, then layer framework validation for complex rules. Use novalidate on the <form> only when your JS validation fully replaces the native UX, and ensure your replacement is accessible.
Best Practices
Associate every input with a visible label. Every form control MUST have a <label> linked via for/id or by wrapping the control inside the <label> element. The placeholder attribute MUST NOT be used as a label substitute -- it disappears on input, provides insufficient contrast in most browsers, and is not reliably announced by all screen readers. A visible label also expands the hit area: clicking it focuses the control.
Prefer native validation attributes over JavaScript. Authors SHOULD declare constraints using required, type, pattern, min, max, minlength, and maxlength before writing any validation script. Native constraints are enforced before any JavaScript runs, integrate automatically with the browser's accessibility infrastructure, and participate in the :invalid / :user-invalid pseudo-class cascade without additional code. JavaScript validation SHOULD supplement native constraints for complex cross-field or async rules, not replace them.
Always validate on the server. Client-side validation MUST be treated as a UX layer only, never as a security boundary. Any client can bypass JavaScript or submit crafted requests directly to the endpoint. The server MUST independently validate every submitted value.
Group related controls with fieldset and legend. Radio buttons, checkboxes, and semantically related fields (e.g., address sub-fields) SHOULD be wrapped in <fieldset> with a descriptive <legend>. Without this grouping, a screen reader announces "Yes, radio button" with no context; with it, the reader announces "Subscribe to newsletter? Yes, radio button." AVOID relying on visual proximity alone to imply grouping.
Declare autocomplete on personal-data inputs. Any input that accepts a name, email address, phone number, postal address, or payment detail SHOULD carry the appropriate autocomplete token (e.g., email, street-address, cc-number). This enables browser autofill, reduces keystrokes for motor-impaired users, and is required for WCAG 2.1 SC 1.3.5 (Identify Input Purpose) at Level AA.
Use novalidate only when your JS validation fully replaces native UX. Adding novalidate to a <form> suppresses all built-in browser validation UI. AVOID using it unless the custom validation layer covers every constraint, provides accessible error announcements (aria-describedby, role="alert"), manages focus to the first invalid field, and handles the submission-prevention logic that native validation would have provided.
Visual
Form lifecycle
The form lifecycle flows from user input through three validation layers: native HTML constraints checked by the browser, the Constraint Validation API for custom JavaScript rules, and server-side validation as the final authority. Errors at any stage redirect the user back to correct their input.
Example
1. Form with native validation and :user-valid styling
<style>
/* Only show validation styles after user interaction */
input:user-valid,
select:user-valid,
textarea:user-valid {
border-color: #2e7d32;
outline-color: #2e7d32;
}
input:user-invalid,
select:user-invalid,
textarea:user-invalid {
border-color: #c62828;
outline-color: #c62828;
}
/* Fallback for older browsers */
@supports not selector(:user-valid) {
input:valid:not(:placeholder-shown) {
border-color: #2e7d32;
}
input:invalid:not(:placeholder-shown):not(:focus) {
border-color: #c62828;
}
}
</style>
<form action="/register" method="POST">
<fieldset>
<legend>Create Account</legend>
<div>
<label for="username">Username</label>
<input id="username" name="username" type="text"
required minlength="3" maxlength="20"
pattern="[a-zA-Z0-9_]+"
autocomplete="username"
placeholder=" " />
</div>
<div>
<label for="user-email">Email</label>
<input id="user-email" name="email" type="email"
required
autocomplete="email"
placeholder=" " />
</div>
<div>
<label for="user-password">Password</label>
<input id="user-password" name="password" type="password"
required minlength="12"
autocomplete="new-password"
placeholder=" " />
</div>
<div>
<label for="user-role">Role</label>
<select id="user-role" name="role" required>
<option value="">-- Select a role --</option>
<option value="developer">Developer</option>
<option value="designer">Designer</option>
<option value="manager">Manager</option>
</select>
</div>
<button type="submit">Create Account</button>
</fieldset>
</form>The :user-valid and :user-invalid pseudo-classes only apply after the user has interacted with the field -- no red borders on page load. The @supports block provides a fallback using the :placeholder-shown trick for older browsers.
2. FormData API extraction
<form id="contact-form" action="/contact" method="POST">
<label for="contact-name">Name</label>
<input id="contact-name" name="name" type="text" required />
<label for="contact-email">Email</label>
<input id="contact-email" name="email" type="email" required />
<label for="contact-subject">Subject</label>
<select id="contact-subject" name="subject">
<option value="support">Support</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
<label for="contact-message">Message</label>
<textarea id="contact-message" name="message" required></textarea>
<button type="submit">Send</button>
</form>
<script>
const form = document.getElementById('contact-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
// FormData reads all named controls automatically
const formData = new FormData(form);
// Access individual values
const name = formData.get('name'); // string
const email = formData.get('email'); // string
// Convert to a plain object
const data = Object.fromEntries(formData);
// { name: "Alice", email: "alice@example.com", subject: "support", message: "..." }
// Submit as JSON
const response = await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!response.ok) {
// Handle server validation errors
}
});
</script>FormData reads all named form controls without manually querying each one. It works with all form control types, including file inputs (formData.get('file') returns a File object). For multipart submissions (file uploads), pass FormData directly as the fetch body without setting Content-Type -- the browser sets the correct boundary.
3. Accessible error messaging with Constraint Validation API
<form id="signup-form" action="/signup" method="POST" novalidate>
<div>
<label for="signup-email">Email address</label>
<input id="signup-email" name="email" type="email" required
autocomplete="email"
aria-describedby="email-error" />
<p id="email-error" role="alert" hidden></p>
</div>
<div>
<label for="signup-age">Age</label>
<input id="signup-age" name="age" type="number"
min="13" max="120" required
aria-describedby="age-error" />
<p id="age-error" role="alert" hidden></p>
</div>
<button type="submit">Sign Up</button>
</form>
<script>
const form = document.getElementById('signup-form');
function showError(input, message) {
const errorEl = document.getElementById(
input.getAttribute('aria-describedby')
);
errorEl.textContent = message;
errorEl.hidden = false;
input.setAttribute('aria-invalid', 'true');
}
function clearError(input) {
const errorEl = document.getElementById(
input.getAttribute('aria-describedby')
);
errorEl.textContent = '';
errorEl.hidden = true;
input.removeAttribute('aria-invalid');
}
function validateField(input) {
// Use the Constraint Validation API
if (input.validity.valueMissing) {
showError(input, `${input.labels[0].textContent} is required.`);
return false;
}
if (input.validity.typeMismatch) {
showError(input, 'Please enter a valid email address.');
return false;
}
if (input.validity.rangeUnderflow) {
showError(input, `Must be at least ${input.min}.`);
return false;
}
if (input.validity.rangeOverflow) {
showError(input, `Must be at most ${input.max}.`);
return false;
}
// Custom async-style validation
input.setCustomValidity('');
clearError(input);
return true;
}
// Validate on blur for immediate feedback
form.querySelectorAll('input').forEach((input) => {
input.addEventListener('blur', () => validateField(input));
input.addEventListener('input', () => {
if (input.getAttribute('aria-invalid')) {
validateField(input);
}
});
});
form.addEventListener('submit', (event) => {
event.preventDefault();
const inputs = [...form.querySelectorAll('input')];
const firstInvalid = inputs.find((input) => !validateField(input));
if (firstInvalid) {
// Focus management: move focus to the first invalid field
firstInvalid.focus();
return;
}
// All valid -- submit
const data = new FormData(form);
fetch('/api/signup', { method: 'POST', body: data });
});
</script>Key accessibility patterns in this example:
aria-describedbylinks each input to its error message. Screen readers announce the error after the field name and role.aria-invalid="true"tells assistive technology the field has an error.role="alert"on the error element causes screen readers to announce the error immediately when it appears.- Focus management moves focus to the first invalid field on submission, so keyboard users are directed to the problem.
hiddenattribute keeps error elements in the DOM but invisible until needed.
The validity object (from the Constraint Validation API) exposes granular states: valueMissing, typeMismatch, patternMismatch, tooLong, tooShort, rangeUnderflow, rangeOverflow, stepMismatch, badInput, and customError. This lets you write custom messages for each failure type while leveraging the browser's built-in validation logic.
Deep Dive
The Constraint Validation API lifecycle
Every form control that participates in constraint validation exposes a validity property -- a ValidityState object -- and two methods: checkValidity() and reportValidity(). Understanding the difference between them matters for building custom validation UIs.
checkValidity() runs the browser's internal constraint checks and returns true if all constraints pass, false otherwise. When it returns false it fires a cancellable invalid event on the control. This method does not change the UI -- it does not show the browser's native error tooltip. It is what you call when you want to know whether a field is valid and then render your own error message.
reportValidity() does the same check but also shows the browser's native validation UI (the error bubble) if the field is invalid. Use it when you want the browser's default error presentation. AVOID calling reportValidity() inside a novalidate form where you have committed to custom error UI, because the native tooltip will appear unexpectedly.
The invalid event fires on a control when checkValidity() or reportValidity() finds a constraint violation, or when the form attempts to submit and finds an invalid field. It does not bubble, so you must attach listeners per-field (or use capture). The invalid event is the native hook for custom validation UI -- listen to it instead of duplicating the submit-time loop yourself.
ValidityState properties represent the specific reason a field is invalid. The full set:
| Property | Condition |
|---|---|
valueMissing | required is set and the value is empty |
typeMismatch | Value does not match the type format (e.g., not a valid email) |
patternMismatch | Value does not match the pattern regex |
tooLong | Value exceeds maxlength |
tooShort | Value is shorter than minlength |
rangeUnderflow | Numeric value is below min |
rangeOverflow | Numeric value is above max |
stepMismatch | Value is not a valid step multiple |
badInput | Browser cannot convert the raw input to the type (e.g., partial date) |
customError | setCustomValidity() was called with a non-empty string |
valid | All constraints pass (all above are false) |
The novalidate + custom UI pattern. When you add novalidate to the <form> and suppress native submission validation, you take on the entire validation pipeline: call checkValidity() (or iterate validity states) per field, populate error messages, set aria-invalid="true", announce errors via role="alert" or aria-live, and move focus to the first invalid field. The invalid event is still fired by checkValidity(), so you can use an event listener on the form (capture phase) to centralize error rendering. Call setCustomValidity('') to clear a custom error before re-running validation, otherwise customError stays true permanently.
Common Mistakes
1. div + click handler instead of button type="submit"
<!-- WRONG: not focusable, no keyboard support, no form submission -->
<div class="btn" onclick="submitForm()">Submit</div>Impact. The <div> has no button role in the accessibility tree, is not keyboard focusable, does not respond to Enter/Space, and does not trigger native form submission or validation.
Fix. Use a native <button>:
<button type="submit">Submit</button>Related FEEs
| FEE | Relationship |
|---|---|
| FEE-100 HTML & Semantic Markup Overview | Parent overview. Forms are one of the key interactive areas of HTML covered in the overview. |
| FEE-102 Semantic Elements & Accessibility | Accessibility foundations. Label association, ARIA live regions for error announcements, and accessible name computation are covered there. |
| FEE-106 HTML APIs & Progressive Enhancement | Progressive enhancement. SvelteKit form actions and framework approaches to forms that work without JS are expanded there. |
References
- WHATWG HTML Living Standard -- Forms -- The authoritative specification for form elements, input types, validation constraints, and submission
- WHATWG HTML Living Standard -- Constraint Validation -- Specification for the Constraint Validation API (checkValidity, reportValidity, setCustomValidity, ValidityState)
- MDN: Web Forms Guide -- Comprehensive learning guide covering form structure, validation, styling, and accessibility
- MDN: Constraint Validation -- Reference for HTML validation attributes and the Constraint Validation API
- MDN: FormData API -- Reference for the FormData interface used to construct key/value pairs from form controls
- MDN: :user-valid -- Reference for the :user-valid pseudo-class that matches after user interaction
- web.dev: Learn Forms -- Practical course on form design, validation, accessibility, and security
- web.dev: :user-valid and :user-invalid pseudo-classes -- Explanation of interaction-gated validation styling
- W3C WAI: Accessible Forms -- Tutorial on building accessible forms with labels, grouping, instructions, and error handling
- SvelteKit Docs: Form Actions -- SvelteKit's progressive enhancement approach to form handling