无障碍表单教程

无论使用哪种框架,每个 Lily 表单都遵循同一模式:为每个控件加标签,提交时检查,把每个错误放在对应字段旁,并在焦点落下处汇总错误。

你将构建什么

一个两字段的表单:带错误提交时,它会在每个字段旁和顶部的摘要中说明哪里有误,并把焦点移到摘要,让键盘或读屏用户立即找到错误。示例使用带 Lily 类名的纯 HTML;每个框架的组件库都会用自己的 Field、 Hint、 ErrorMessage 和 ErrorSummary 组件输出相同的标记。约 20 分钟;建议先完成 HTML 教程 。

第 1 步 — 为每个控件加标签,并说明期望的内容

<form class="form" novalidate>
  <div class="field">
    <label class="label" for="name">Full name</label>
    <input class="text-input" type="text" id="name" name="name" autocomplete="name" required />
  </div>
  <div class="field">
    <label class="label" for="email">Email</label>
    <p class="hint" id="email-hint">We only use this to send your appointment.</p>
    <input class="email-input" type="email" id="email" name="email"
      autocomplete="email" aria-describedby="email-hint" required />
  </div>
  <button class="button" type="submit">Continue</button>
</form>
  • 每个控件都要有可见的 <label for> ,绝不用占位文字代替:占位文字一输入就会消失。
  • 提示通过 aria-describedby与字段名称关联,因此读屏软件会连同字段一起朗读。
  • autocomplete 让浏览器填写它已知的信息(WCAG 1.3.5)。
  • novalidate 会关闭浏览器自带的气泡提示,因为你将用自己的语言和措辞显示错误。 required 和 type 保留:你的脚本会读取它们。

第 2 步 — 提交时检查,而不是输入时

刚输入一个字母就说邮箱错误只是干扰。请在提交时检查。63 个主题只会在字段被编辑并离开后(:user-invalid),或你设置 aria-invalid="true"时才显示为无效,所以页面加载时不会有任何内容变红。

在表单有效之前,绝不要禁用提交按钮:禁用的按钮无法说明原因。

第 3 步 — 把每个错误放在对应字段旁

<div class="field">
  <label class="label" for="email">Email</label>
  <p class="hint" id="email-hint">We only use this to send your appointment.</p>
  <p class="error-message" id="email-error">Enter an email address in the right format, like name@example.com</p>
  <input class="email-input" type="email" id="email" name="email" autocomplete="email"
    aria-invalid="true" aria-describedby="email-hint email-error" required />
</div>
  • aria-invalid="true" 表明字段有误;消息说明原因和改正方法。
  • 消息列在 aria-describedby中,位于提示之后,因此字段获得焦点时会被朗读。
  • 说明该怎么做,而不只是哪里错了:要说“请输入格式正确的电子邮件地址”,而不是“无效”。
  • 绝不只靠颜色:文字才是错误本身;红色边框只是重复它(WCAG 1.4.1)。

第 4 步 — 在焦点落下处汇总错误

<div class="error-summary" role="alert" tabindex="-1" aria-labelledby="error-summary-title">
  <h2 id="error-summary-title">There is a problem</h2>
  <ul>
    <li><a href="#name">Enter your full name</a></li>
    <li><a href="#email">Enter an email address in the right format, like name@example.com</a></li>
  </ul>
</div>

把它放在表单顶部,提交时把焦点移到它。每个链接直接通向对应字段。 tabindex="-1" 让摘要可以获得焦点,而不增加一个 Tab 停靠点。

第 5 步 — 把一切连起来的脚本

const messages = {
  name: { valueMissing: "Enter your full name" },
  email: {
    valueMissing: "Enter your email address",
    typeMismatch: "Enter an email address in the right format, like name@example.com",
  },
};

const form = document.querySelector("form");
form.addEventListener("submit", (event) => {
  form.querySelector(".error-summary")?.remove();
  const errors = [];
  for (const field of form.querySelectorAll("input")) {
    const old = document.getElementById(field.id + "-error");
    old?.remove();
    const describedBy = (field.getAttribute("aria-describedby") ?? "")
      .split(" ").filter((id) => id && id !== field.id + "-error");
    const problem = Object.keys(messages[field.name] ?? {}).find((key) => field.validity[key]);
    if (!problem) {
      field.removeAttribute("aria-invalid");
      field.setAttribute("aria-describedby", describedBy.join(" "));
      continue;
    }
    const text = messages[field.name][problem];
    const message = document.createElement("p");
    message.className = "error-message";
    message.id = field.id + "-error";
    message.textContent = text;
    field.before(message);
    field.setAttribute("aria-invalid", "true");
    field.setAttribute("aria-describedby", [...describedBy, message.id].join(" "));
    errors.push({ id: field.id, text });
  }
  if (errors.length === 0) return; // valid: let it submit
  event.preventDefault();
  const summary = document.createElement("div");
  summary.className = "error-summary";
  summary.setAttribute("role", "alert");
  summary.tabIndex = -1;
  summary.setAttribute("aria-labelledby", "error-summary-title");
  summary.innerHTML = '<h2 id="error-summary-title">There is a problem</h2><ul></ul>';
  for (const { id, text } of errors) {
    const link = document.createElement("a");
    link.href = "#" + id;
    link.textContent = text;
    const item = document.createElement("li");
    item.append(link);
    summary.querySelector("ul").append(item);
  }
  form.prepend(summary);
  summary.focus();
});

消息由你决定,用你的语言:浏览器的 validity 说明哪条规则未通过,你的表格说明要告诉用户什么。Lily 不附带任何需要翻译的英文文字。

检查成果: 用键盘提交空表单。焦点移到摘要,读屏软件朗读“There is a problem”和两条错误。点开一个链接:焦点落到字段,连同提示和错误一起被朗读。改正两处后提交:表单顺利提交,不留任何错误。

应当避免

  • 在不告知的情况下限制或修改用户输入的内容;应当告诉对方。
  • 出错时清空表单:保留用户已输入的一切。
  • 只在悬停时或只在工具提示中出现的错误。
  • 不加警告就让表单超时;请使用 timeout-dialog 进行警告并延长时间。

下一步