WebDev Story

WebDev Story: HTML Forms

structure, input types, validation, submission

4.0 Form Structure

An HTML form is a collection of controls that gathers user input and submits it to a server or handles it with JavaScript. The <form> element is the container; every control inside it participates in submission.
<form id="signup" action="/submit" method="post">
  <label for="name">Name</label>
  <input type="text" id="name" name="name" required>

  <label for="email">Email</label>
  <input type="email" id="email" name="email" required>

  <button type="submit">Sign Up</button>
</form>
The two most important <form> attributes:
  • action — URL the form data is sent to on submission. Omit (or set to "") when JavaScript handles submission.
  • methodget appends data to the URL as a query string; post sends it in the request body. Use post for anything sensitive or large.

4.1 Labels, Fieldsets, and Legends

Associating a <label> with a control via its for attribute (matching the control's id) improves usability: clicking the label focuses the control, and screen readers announce the label text.
<fieldset>
  <legend>Shipping Address</legend>

  <label for="street">Street</label>
  <input type="text" id="street" name="street">

  <label for="city">City</label>
  <input type="text" id="city" name="city">
</fieldset>
<fieldset> visually groups related controls; <legend> labels the group. Both improve accessibility and structure.

4.2 Input Types

The type attribute on <input> selects both the control widget and the validation behavior. The browser renders the appropriate UI and rejects values that don't match the type.
Input Type Reference
type= Behavior and notes
textSingle-line free text (default when type is omitted).
passwordMasked text; value is not shown.
emailValidates a basic email address format.
urlValidates a URL.
telPhone number; no format validation, but mobile keyboards show dialpad.
numberNumeric spinner; accepts min, max, step.
rangeSlider between min and max.
dateCalendar date picker (YYYY-MM-DD).
timeTime picker (HH:MM).
datetime-localDate and time combined, without timezone.
monthYear and month picker.
weekYear and ISO week number picker.
colorColor picker; value is a hex color string.
checkboxToggle; submitted only when checked.
radioOne choice from a group sharing the same name.
fileFile chooser; add multiple for multi-file select.
hiddenNot shown; sends a name/value pair silently.
submitButton that submits the form.
resetButton that resets all controls to their initial values.
buttonGeneric button with no default behavior; wire with JavaScript.
imageGraphical submit button using an image source.
searchSearch field; may show a clear button in some browsers.
Other controls complement <input>:
  • <textarea> — multi-line text with rows and cols sizing.
  • <select> — dropdown list of <option> elements; add multiple for a list box.
  • <datalist> — provides autocomplete suggestions for a linked <input> via the list attribute.
  • <button> — more flexible than <input type="button">; its body can contain markup.
  • <output> — displays a computed result, linked to source controls via for.

4.3 Constraint Validation

The browser validates form controls automatically before submission when constraint attributes are present. Validation fails silently until the user tries to submit; the browser then shows native error tooltips and blocks the request.
Constraint Attributes
Attribute Effect
requiredValue must be non-empty before submission.
minlengthMinimum number of characters for text-like inputs.
maxlengthMaximum number of characters; also truncates paste.
minMinimum numeric or date value.
maxMaximum numeric or date value.
stepGranularity for numeric and date inputs.
patternECMAScript regex the entire value must match.
typeImplicitly constrains format (email, url, number, etc.).
To validate programmatically before submission, use the Constraint Validation API:
const form = document.querySelector('#signup');
form.addEventListener('submit', (e) => {
  if (!form.checkValidity()) {
    e.preventDefault();
    form.reportValidity();   // show native tooltips
    return;
  }
  // proceed with valid data
});
Individual controls expose validity (a ValidityState object), validationMessage, and setCustomValidity(msg) for custom error text.

4.4 Form Submission

The default submit action navigates the page to the action URL. JavaScript intercepts it with preventDefault() and then sends data with fetch. FormData collects all named control values automatically.
form.addEventListener('submit', async (e) => {
  e.preventDefault();
  const data = new FormData(form);     // collects all name/value pairs

  const resp = await fetch('/api/signup', {
    method: 'POST',
    body: data
  });

  if (resp.ok) {
    console.log('submitted successfully');
  }
});
FormData also lets you read or modify values before sending:
data.get('email');           // read a value
data.set('name', 'Alice');   // override a value
data.append('tag', 'web');   // add an extra key/value
To send JSON instead of multipart form data, convert FormData to a plain object and serialize it:
const body = JSON.stringify(Object.fromEntries(data));
const resp = await fetch('/api/signup', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body
});

4.5 Form Element Reference

Form Elements
Element Purpose Key Attributes
<form>Form containeraction, method, enctype, novalidate
<input>Single-value controltype, name, value, placeholder, required, disabled, readonly
<textarea>Multi-line textname, rows, cols, maxlength, placeholder
<select>Dropdown or list boxname, multiple, size
<option>Choice in selectvalue, selected, disabled
<optgroup>Group of optionslabel, disabled
<datalist>Autocomplete sourceid (linked via input list)
<button>Clickable buttontype (submit/reset/button), name, value, disabled
<label>Control labelfor (matches control id)
<fieldset>Control groupdisabled (disables all children)
<legend>Fieldset caption
<output>Computed resultfor, name
<progress>Completion barvalue, max
<meter>Scalar gaugevalue, min, max, low, high, optimum

4.6 Tutorials

HTML Forms Tutorials
Tutorial Type Why Use It
MDN: Web Forms Beginner→Advanced Complete series covering structure, styling, validation, and custom controls.
web.dev: Learn Forms Intermediate Deep dive into accessible, robust forms from the Chrome team.
w3schools HTML Forms Beginner Quick reference with interactive examples for each input type.
MDN: Constraint Validation Intermediate Full documentation of the Constraint Validation API.
web.dev: Autofill Practical How to use autocomplete attributes for better UX and password managers.
WebAIM: Accessible Forms Accessibility Labeling, grouping, and error handling for screen readers.

4.7 References

HTML Forms References
Resource Description
MDN: <form> Complete reference for the form element, its attributes, and events.
MDN: <input> All 22 input types with attributes, examples, and browser compatibility.
MDN: FormData API FormData constructor, methods, and use with fetch.
MDN: ValidityState Properties on the validity object returned by each form control.
HTML Living Standard: Forms Authoritative specification for all form elements and the constraint validation algorithm.
w3schools: Form Attributes Quick list of all attributes on the form element.