Introduction to Web Technologies (HTML, CSS, JS)

Chapter 5
Forms, Validation, and Accessibility

Diploma in Full Stack Programming
Introduction to Web Technologies (HTML, CSS, JS)   •   Diploma

Forms, Validation, and Accessibility

Introduction

Web forms are the principal interface through which users provide information to websites and web applications. Account registration, sign-in, searching, purchasing, booking, feedback, and administrative workflows all depend on forms. A form is therefore more than a collection of input boxes: it is an interaction system that must communicate purpose, accept valid data, prevent avoidable errors, protect privacy, and remain usable across devices and assistive technologies.

Accessible form design combines semantic HTML, appropriate controls, clear instructions, robust validation, understandable feedback, keyboard support, and inclusive visual design. HTML provides the structural meaning; CSS provides presentation; JavaScript can improve interaction, but must not be the only means by which a form works. The objective is progressive enhancement: a form should remain understandable and submit correctly even when scripting is unavailable or fails.

This chapter uses the Web Content Accessibility Guidelines (WCAG) and the Web Accessibility Initiative Accessible Rich Internet Applications (WAI-ARIA) as important reference frameworks. WCAG is organized around four principles: content should be perceivable, operable, understandable, and robust. These principles apply directly to form design.

Learning Objectives

By the end of this chapter, you should be able to:

  • select appropriate HTML form controls and input types;
  • associate labels, instructions, groups, and descriptions correctly;
  • distinguish browser constraint validation from server-side validation;
  • design useful error messages and error-recovery processes;
  • explain the role and limits of WAI-ARIA;
  • implement keyboard-accessible and responsive forms;
  • apply inclusive design principles based on WCAG;
  • evaluate a form for usability, accessibility, security, and privacy.

The Form Processing Model

A form has three related dimensions:

  1. Presentation: how controls, labels, instructions, and errors are arranged and styled.
  2. Interaction: how users enter, review, correct, and submit information.
  3. Processing: how the browser and server validate, transmit, store, and act on the submitted data.

The typical sequence is:

User enters data → Browser applies constraints → Form is submitted
       ↓                                      ↓
Feedback and correction ← Server validates and processes data

Client-side validation improves immediacy and user experience. It cannot establish trust because users can disable JavaScript, modify requests, or call an endpoint directly. Server-side validation is mandatory for security and data integrity. The server must treat all incoming data as untrusted.

A form submission normally uses one of two HTTP methods. GET places successful control values in the URL query string and is appropriate for retrieval-oriented actions such as searches. POST places data in the request body and is generally used for actions that create or modify server-side state. Neither method automatically encrypts data; confidentiality requires HTTPS. Sensitive values should not be placed in a URL because URLs may be stored in browser history, logs, analytics systems, and referrer data.

Semantic HTML Form Structure

The basic structure is provided by the form element:

<form action="/สมัคร" method="post">
  <!-- controls and submit button -->
</form>

The action attribute identifies the destination, while method identifies how data is sent. A form should normally have a clearly identifiable purpose, often communicated through a heading and introductory text.

Labels and control association

Every user-input control needs a visible, meaningful label. The most reliable association uses matching for and id values:

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

A label provides more than visual text. Screen readers can announce it when the control receives focus, and clicking the label enlarges the effective target area. The name attribute is also important: it identifies the value submitted to the server. An id identifies the element in the document and supports label association; it is not a substitute for name.

A control may also be wrapped by its label:

<label>
  <input type="checkbox" name="terms">
  I agree to the terms and conditions
</label>

Do not use placeholder text as the only label. Placeholder text disappears during input, often has insufficient contrast, and can be mistaken for an example or pre-filled value.

Grouping related controls

fieldset and legend provide semantic grouping for related controls, especially radio buttons and checkboxes:

<fieldset>
  <legend>Preferred contact method</legend>
  <label><input type="radio" name="contact" value="email"> Email</label>
  <label><input type="radio" name="contact" value="phone"> Phone</label>
</fieldset>

All radio buttons in one choice set must share a name. A radio group permits one value; checkboxes permit independent selections. A legend describes the question shared by the controls and prevents users from having to infer context from nearby layout alone.

Instructions and descriptions

Instructions should appear before the control when they affect how the user should respond. For example, a password rule should be stated before or alongside the password field. Additional information can be associated programmatically with aria-describedby, but the visible text remains essential:

<label for="password">Password</label>
<p id="password-help">Use at least 12 characters.</p>
<input id="password" name="password" type="password"
       minlength="12" aria-describedby="password-help">

The aria-describedby relationship causes supporting text to be announced with the control in many assistive technologies. It should reference concise, relevant content rather than a large block of unrelated text.

Choosing Controls and Input Types

The control should match the data and task. Appropriate controls improve keyboard operation, mobile layouts, browser autofill, and error detection.

RequirementSuitable control or typeImportant consideration
Single line of ordinary textinput type="text"Provide a specific label and suitable autocomplete value
Email addressinput type="email"Browser can provide email-oriented keyboard and basic syntax checking
Secret textinput type="password"Offer a carefully designed show/hide option where useful
Telephone numberinput type="tel"Do not impose a single international format without justification
URLinput type="url"Explain whether a scheme such as https:// is required
Dateinput type="date"Consider browser support and provide understandable date conventions
Numeric quantityinput type="number"Use only when spinner semantics are useful; otherwise text with input guidance may be better
Long responsetextareaSpecify an appropriate size and, if needed, a character limit
Fixed alternativesRadio buttons or selectRadio buttons expose all alternatives; select menus save space
Multiple independent choicesCheckboxesLabel each choice clearly
File uploadinput type="file"State accepted formats, size limits, and privacy implications

The autocomplete attribute helps users reuse information and supports users with cognitive or motor difficulties. Examples include name, email, street-address, postal-code, username, and current-password. Autocomplete is not merely a convenience: it can reduce typing, errors, and abandonment.

Use input type="number" cautiously. A number input communicates that the value is mathematically numeric, but phone numbers, account numbers, postal codes, and identification numbers are not quantities. Leading zeros and punctuation may be significant, so these are often better represented as text with an appropriate inputmode.

Validation: Meaning, Timing, and Trust

Validation checks whether submitted data is acceptable for a particular operation. Three distinct ideas should be separated:

  • Syntax validation: Is the value shaped correctly? For example, is a required field non-empty?
  • Semantic validation: Does it make sense? For example, is an end date after a start date?
  • Business validation: Is it permitted by the application? For example, is the selected seat still available?

Native constraint validation

HTML supplies several validation attributes:

  • required prevents an empty value;
  • type provides type-specific checking such as email syntax;
  • minlength and maxlength constrain text length;
  • min and max constrain numeric or date ranges;
  • step defines permitted increments for applicable numeric values;
  • pattern applies a regular-expression constraint;
  • multiple allows multiple values where supported.

Example:

<label for="quantity">Quantity</label>
<input id="quantity" name="quantity" type="number"
       min="1" max="20" step="1" required>

These attributes are useful because they provide a common browser-level foundation and expose constraints to some assistive technologies. However, default browser messages may be inconsistent, overly technical, or poorly localized. Applications should test the resulting experience and provide their own clear feedback where necessary.

pattern is powerful but easy to misuse. A restrictive expression can reject legitimate names, addresses, or international formats. Validation rules should reflect real requirements, not assumptions about language, culture, or identity. Avoid “validating” away valid user data.

JavaScript validation

JavaScript can validate as the user interacts or when the form is submitted. The Constraint Validation API includes checkValidity(), reportValidity(), and setCustomValidity():

<input id="confirm-email" name="confirmEmail" type="email" required>
<script>
const form = document.querySelector('form');
const email = document.querySelector('#email');
const confirmEmail = document.querySelector('#confirm-email');

form.addEventListener('submit', (event) => {
  if (email.value !== confirmEmail.value) {
    confirmEmail.setCustomValidity('Enter the same email address again.');
  } else {
    confirmEmail.setCustomValidity('');
  }

  if (!form.checkValidity()) {
    event.preventDefault();
    form.reportValidity();
  }
});
</script>

Custom validation should identify the specific field and explain how to correct it. It should not prevent submission merely because data is unusual. Avoid validating on every keystroke when that produces distracting or premature errors. A practical pattern is to validate on submission and, after an error has been identified, provide timely feedback when the user revisits or changes the field.

Server-side validation

The server must repeat all important checks. It should validate type, length, allowed values, relationships among fields, authorization, and business rules. It must safely encode output and use parameterized database queries to reduce injection risks. Validation is not sanitization: validation decides whether data is acceptable, while output encoding and safe APIs reduce the risk of interpreting data as code.

Error Feedback and Recovery

Good error handling is a communication process, not simply a red border. An effective error system should:

  1. identify that an error exists;
  2. identify the affected field or fields;
  3. explain what is wrong in plain language;
  4. explain how to correct it;
  5. preserve previously entered valid information;
  6. move focus or provide navigation to the problem without disorienting the user.

A useful inline error might be: “Enter a valid email address, such as [email protected].” It is more helpful than “Invalid input.” Error messages should not blame users or disclose sensitive information. A login system, for example, should avoid revealing whether an email address exists in the database.

An accessible error implementation may look like this:

<label for="postal-code">Postal code</label>
<input id="postal-code" name="postalCode" required
       aria-invalid="true" aria-describedby="postal-error">
<p id="postal-error" class="error" role="alert">
  Enter your postal code.
</p>

aria-invalid="true" communicates the invalid state, but it should be added when the application has actually identified an error, not merely because a field is initially empty. aria-describedby associates the message with the input. role="alert" creates an assertive live region and should be used carefully: announcing many alerts at once can overwhelm screen-reader users. For a group-level summary, a heading and list of links to invalid fields can be effective.

Do not communicate errors through colour alone. Combine colour with text, icons used consistently, borders, and programmatic state. Text and controls must also meet appropriate contrast requirements, and keyboard focus must remain visibly identifiable.

Accessibility and WCAG Principles

Perceivable

Users must be able to perceive labels, instructions, errors, and focus indicators. Provide sufficient contrast, meaningful text alternatives where icons convey information, and responsive layouts that work at increased text size or zoom. Do not hide essential instructions in hover-only interactions.

Operable

All controls must be usable with a keyboard. The normal focus order should follow the visual and logical order. Do not remove the browser focus outline unless replacing it with an equally visible alternative. Ensure that custom widgets support keyboard commands consistently and do not trap focus.

Touch targets should be sufficiently large and separated enough to reduce accidental activation. A small checkbox with a large associated label is usually more usable than a tiny isolated target.

Understandable

Use familiar terminology, predictable layouts, consistent labels, and clear instructions. Identify required fields consistently rather than relying on unexplained symbols. If a session can expire, warn users and provide a way to save or recover their work where appropriate.

Robust

Use native HTML before custom ARIA widgets. Native controls already provide semantics, keyboard behavior, and broad browser support. ARIA can supplement semantics, but it does not automatically supply behavior. The principle often summarized as “No ARIA is better than bad ARIA” is especially important: incorrect roles and states can make a form less accessible than plain HTML.

WAI-ARIA in Forms

WAI-ARIA provides roles, states, and properties that communicate a control’s meaning or state to accessibility APIs. Common form-related attributes include:

  • aria-label: an accessible name when no visible label is available; a visible label is usually preferable;
  • aria-labelledby: names a control using another element’s text;
  • aria-describedby: associates help or error text;
  • aria-required: communicates required status for custom controls, although native required is preferred for native inputs;
  • aria-invalid: indicates that a value has failed validation;
  • aria-expanded: indicates whether an expandable custom component is open;
  • aria-live or role="alert": announces dynamic updates.

ARIA does not submit values, validate data, create focus behavior, or make a clickable div equivalent to a button. A custom combobox, date picker, or modal dialog requires careful implementation of keyboard interaction, focus management, roles, states, and announcements. For diploma-level development, native select, input, button, and dialog elements should be preferred whenever they meet the requirement.

Submission Controls and Interaction Design

A submit button should state its action, such as “Create account,” “Send application,” or “Search,” rather than using vague text such as “Click here.” The button must be a real button or submit input, not a styled paragraph or div.

Preventing duplicate submissions can be useful, especially for payments, but disabling a button too early can prevent correction or leave users without feedback. If submission takes time, expose a clear progress state and ensure that users are informed when the operation succeeds or fails. A disabled control may be impossible to discover or activate with a keyboard, so explain why an action is unavailable when that information matters.

Success feedback should be as accessible as error feedback. After submission, communicate the result in the page title, a visible heading, and, where appropriate, a polite live region. Do not rely only on a colour change or a temporary animation.

Privacy, Security, and Ethical Considerations

Forms routinely collect personal data. Professional developers should apply data minimization: request only information needed for a stated purpose. Explain why sensitive information is collected, how it will be used, retention periods where relevant, and who may receive it.

Important safeguards include:

  • HTTPS for data in transit;
  • server-side validation and authorization;
  • protection against cross-site request forgery where applicable;
  • secure password hashing rather than reversible storage;
  • careful handling of uploaded files;
  • avoidance of sensitive data in URLs and logs;
  • rate limiting and abuse detection;
  • privacy-respecting analytics and consent mechanisms.

Accessibility and security sometimes interact. CAPTCHA systems can exclude users with disabilities; alternatives such as risk-based detection, accessible verification flows, or human-assisted recovery should be considered. Required fields should not demand unnecessary identity or demographic information, and forms should support diverse names, addresses, languages, and family structures.

Applied Case: Accessible Course-Enrolment Form

Background. A college’s course-enrolment form asks students for personal information, course choices, emergency contact details, and payment preferences. Students report that the form is difficult to use on mobile devices, errors disappear after submission, and screen-reader users cannot identify which radio-button group is being announced.

Problem. The original form uses placeholder text as labels, a series of unlabelled custom dropdowns, client-side-only validation, red borders without text, and a single generic message at the top: “Please correct the errors.”

Analysis. The failures affect all four WCAG principles. The missing labels reduce perceivability and robustness; custom controls create operability problems; generic errors reduce understandability; and client-only checks compromise robust processing and data integrity.

Approach. The development team redesigns the form as follows:

  • visible label elements are associated with every native control;
  • related choices use fieldset and legend;
  • native select, radio, checkbox, date, and text controls replace unnecessary custom widgets;
  • autocomplete tokens reduce typing;
  • HTML constraints provide immediate basic checks;
  • the server repeats validation and returns field-specific errors;
  • an error summary links to each invalid field;
  • invalid fields use aria-invalid and aria-describedby only when errors exist;
  • focus moves to the summary after a failed submission, while each summary link moves focus to its field;
  • errors use text and structure, not colour alone;
  • entered values are preserved after a server response;
  • the form is tested with keyboard-only navigation, browser zoom, mobile layouts, and screen readers.

Outcome. Students can complete the form more reliably, error correction requires fewer steps, and the institution receives more consistent data. The solution also reduces maintenance because native controls provide much of the expected keyboard and accessibility behaviour.

Learning points. Accessibility is most effective when designed into the information structure rather than added through visual styling at the end. Native HTML, clear language, progressive enhancement, and server-side validation provide a strong professional foundation.

Testing and Evaluation

A form should be tested using several complementary methods:

  1. Keyboard test: Can a user reach every control, understand focus, operate widgets, and submit without a mouse?
  2. Screen-reader test: Are labels, group names, instructions, states, errors, and success messages announced meaningfully?
  3. Visual test: Are contrast, focus indicators, error text, zoom, reflow, and spacing adequate?
  4. Input test: Are empty, boundary, malformed, unusually long, international, and unexpected values handled appropriately?
  5. Network and security test: Does the server reject invalid or unauthorized requests? Are sensitive values protected?
  6. User test: Can people with different abilities and levels of technical experience complete realistic tasks?

Automated accessibility tools can identify missing labels, invalid ARIA references, and some contrast problems, but they cannot determine whether a label is understandable, whether an error is helpful, or whether a workflow is cognitively manageable. Conformance checking is therefore necessary but insufficient; human evaluation remains essential.

Contemporary Developments and Professional Practice

Modern web applications increasingly use component frameworks and dynamic interfaces. These technologies can improve consistency but may also obscure native semantics, reset focus unexpectedly, and render errors outside the user’s current context. Component libraries should document their keyboard behaviour, accessible names, state changes, and validation APIs.

Design systems can standardize labels, help text, error summaries, buttons, focus styles, and spacing. However, standardization must not become rigid exclusion: date formats, names, addresses, and communication preferences may require regional and cultural flexibility.

AI-assisted form completion and document extraction can reduce repetitive entry, but such systems must disclose automation, allow correction, protect personal data, and avoid making consequential decisions without meaningful review. Predictions should never silently overwrite user input. Developers remain responsible for the resulting experience, including errors produced by automated tools.

Best-Practice Checklist

Before releasing a form, verify that:

  • every control has a visible, correctly associated label;
  • required status and instructions are clear before entry;
  • controls match the type of information requested;
  • name attributes are present for submitted values;
  • autocomplete supports common personal details;
  • browser constraints are supplemented by server-side validation;
  • errors identify fields and explain correction steps;
  • errors are not communicated by colour alone;
  • focus order and keyboard operation are logical;
  • custom widgets are avoided unless genuinely necessary;
  • ARIA supplements rather than replaces native semantics;
  • valid input is preserved after errors;
  • success and failure states are announced accessibly;
  • personal data collection is necessary, secure, and explained;
  • the form has been tested with automated tools and real users.

Chapter Summary

Accessible forms are structured communication systems as well as data-entry mechanisms. Semantic HTML supplies the foundation: form, label, fieldset, legend, native controls, and meaningful buttons provide reliable names, relationships, and behaviours. Input types, autocomplete tokens, and constraint attributes improve usability, but they do not replace server-side validation.

Validation should address syntax, meaning, and business rules. Client-side checks offer immediate feedback; server-side checks protect application integrity. Effective error handling identifies the problem, explains a correction, preserves valid input, and communicates status through text, focus, and appropriate accessibility properties. WCAG’s principles of perceivable, operable, understandable, and robust content provide a practical evaluation framework.

WAI-ARIA is valuable for supplementing dynamic interfaces, but it does not create behaviour or compensate for poor HTML. Native controls should be preferred. Professional form development also requires keyboard testing, screen-reader testing, responsive design, privacy protection, secure processing, data minimization, and respect for diverse users. The strongest implementation is inclusive by design, progressively enhanced, and tested in realistic contexts.

Key Terms

Semantic HTML: HTML that conveys the meaning and structure of content through appropriate elements.

Form control: An interactive element through which a user enters or selects data.

Label: Visible text that names and explains a form control.

Fieldset: An element that groups related form controls.

Legend: The caption that identifies a fieldset.

Constraint validation: Browser-supported checking based on attributes such as required, min, and pattern.

Client-side validation: Validation performed in the browser before or during submission.

Server-side validation: Validation performed by the receiving application server.

Syntax validation: Checking whether data has an acceptable structure.

Semantic validation: Checking whether data makes sense in context.

Business validation: Checking whether data satisfies application rules.

Accessible name: The programmatically determinable name announced for a control.

aria-describedby: An ARIA property associating a control with explanatory or error text.

aria-invalid: An ARIA state indicating that a control’s value has failed validation.

Progressive enhancement: Building a functional basic experience first, then adding optional enhancements.

WCAG: Web Content Accessibility Guidelines.

WAI-ARIA: Web Accessibility Initiative Accessible Rich Internet Applications specification.

Focus order: The sequence in which interactive elements receive keyboard focus.

Data minimization: Collecting only the personal data necessary for a stated purpose.

Autocomplete: A browser-supported mechanism for suggesting or filling known types of information.

Review Questions

Short Answer Questions

  1. Why should every form control have a visible label, and how can it be associated programmatically with an input?
  2. Distinguish client-side validation from server-side validation.
  3. What are the purposes of fieldset and legend?
  4. Why should placeholder text not be the only label for a control?
  5. State two appropriate uses of aria-describedby.

Long Answer Questions

  1. Explain how the four WCAG principles apply to an online registration form.
  2. Describe a complete error-feedback strategy for a form containing five invalid fields.
  3. Compare radio buttons, checkboxes, select menus, and text inputs, including when each is appropriate.
  4. Explain why native HTML controls are generally preferable to custom ARIA widgets.
  5. Discuss the relationship between form accessibility, privacy, and security.

Analytical / Application Questions

  1. Evaluate a checkout form that uses placeholder-only labels, red borders without text, and JavaScript-only validation. Identify the risks and propose a redesign.
  2. Design the semantic structure and validation approach for a course-enrolment form containing personal details, a course choice, optional accommodations, and an emergency contact.
  3. A product team wants to replace a native date input with a custom calendar widget. Analyse the accessibility and maintenance implications and recommend a decision process.

Multiple Choice Questions with Answers

Question 1

Which attribute identifies the value submitted for a form control?

A. id

B. name

C. class

D. title

Correct Answer: B. name

Question 2

Which element provides a caption for a group of related form controls?

A. caption

B. legend

C. summary

D. heading

Correct Answer: B. legend

Question 3

Why is server-side validation essential?

A. It makes labels unnecessary

B. It prevents all network failures

C. Client-side checks can be bypassed or modified

D. It automatically improves colour contrast

Correct Answer: C. Client-side checks can be bypassed or modified

Question 4

Which control is generally most appropriate for choosing exactly one option from a small visible set?

A. Checkbox group

B. Radio-button group

C. Textarea

D. File input

Correct Answer: B. Radio-button group

Question 5

What is the primary purpose of aria-describedby in a form?

A. To submit an additional value

B. To associate explanatory or error text with a control

C. To make a control keyboard accessible automatically

D. To encrypt input data

Correct Answer: B. To associate explanatory or error text with a control

Question 6

Which is the best error message for an incorrectly formatted email field?

A. Error

B. Invalid input

C. You failed validation

D. Enter a valid email address, such as [email protected].

Correct Answer: D. Enter a valid email address, such as [email protected].

Question 7

What does the HTTP GET method generally place in the URL?

A. The request query parameters

B. The server’s password hash

C. The response headers only

D. The browser’s accessibility tree

Correct Answer: A. The request query parameters

Question 8

Which practice best supports keyboard accessibility?

A. Removing all focus indicators

B. Using clickable div elements instead of buttons

C. Maintaining a logical focus order and visible focus indicator

D. Requiring mouse hover before submission

Correct Answer: C. Maintaining a logical focus order and visible focus indicator

Question 9

What does aria-invalid="true" communicate?

A. That a field is hidden

B. That a field’s value has failed validation

C. That a field is read-only

D. That a field is optional

Correct Answer: B. That a field’s value has failed validation

Question 10

Which principle means that a form should work with a wide range of browsers and assistive technologies?

A. Perceivable

B. Operable

C. Understandable

D. Robust

Correct Answer: D. Robust

Introduction to Web Technologies (HTML, CSS, JS)
Chapter 5 of 15