Open in a new tab

A schema-validated sign-up form: errors are announced and linked to their fields, focus moves to the first invalid field, and a valid submit shows the payload it would send (nothing is sent).

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Every form that real people fill in: validation from one schema, messages a screen reader announces and a sighted user sees next to the field, focus where the fix is needed, and a submit handler that only runs on valid data.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Replace SCHEMA and the field list; keep one <span id="<name>-error"> per field and a novalidate form so fw's messages are the ones shown.

What it shows

  • formKit.create({ schema, defaultValues }) on top of form: the controller is fk.form, attach(name, element) keeps DOM and values in sync, submit(onValid, onInvalid) validates first.
  • a11y.aria(el, { invalid }), a11y.describedBy(el, ids) and a11y.announce(text, 'assertive') through fw's live regions.
  • focus.tabOrder(form) to find the first invalid field in visual order and focus.pushFocus(el) to move there.
  • Errors come from the schema (minLength, format: 'email'), keyed by field.

Code

main.js

javascriptApache-2.073 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { form } from '@awacloud/fw/dom/utils/form.js';
import { formKit } from '@awacloud/fw/dom/utils/formKit.js';
import { a11y } from '@awacloud/fw/dom/utils/a11y.js';
import { focus } from '@awacloud/fw/dom/utils/focus.js';

fw.runtime.registerAllDeep([form, formKit, a11y, focus]);
const A11Y = fw.runtime.resolve('a11y');
const FOCUS = fw.runtime.resolve('focus');

export const FIELDS = ['name', 'email', 'password'];
export const SCHEMA = {
    type: 'object',
    required: FIELDS,
    properties: {
        name: { type: 'string', minLength: 2, maxLength: 60 },
        email: { type: 'string', format: 'email' },
        password: { type: 'string', minLength: 8 },
    },
};

/** formKit wraps `form` (the controller is `fk.form`) and validates with `valid`. */
export const fk = fw.runtime.resolve('formKit').create({
    schema: SCHEMA,
    defaultValues: { name: '', email: '', password: '' },
});
const element = /** @type {HTMLFormElement} */ (document.getElementById('signup'));
/** @param {string} name */
const input = (name) => /** @type {HTMLInputElement} */ (element.elements.namedItem(name));
for (const name of FIELDS) fk.form.attach(name, input(name));

/**
 * Show or clear the errors, link each message to its field, move focus to
 * the first invalid field in tab order and announce the count.
 * @param {Record<string, string>} errors field → message
 * @returns {string[]} the invalid field names, in tab order
 */
export function showErrors(errors) {
    const invalid = FOCUS.tabOrder(element).map((el) => el.getAttribute('name') ?? '').filter((name) => errors[name]);
    for (const name of FIELDS) {
        const message = errors[name] ?? '';
        /** @type {HTMLElement} */ (document.getElementById(`${name}-error`)).textContent = message;
        A11Y.aria(input(name), { invalid: message ? 'true' : null });
        A11Y.describedBy(input(name), message ? [`${name}-error`] : []);
    }
    if (invalid.length) {
        FOCUS.pushFocus(input(invalid[0]));
        A11Y.announce(`${invalid.length} field${invalid.length > 1 ? 's need' : ' needs'} attention`, 'assertive');
    }
    return invalid;
}

/** Nothing is sent: the payload that would go to the server is shown instead. */
export function submit() {
    return fk.submit(
        (values) => {
            showErrors({});
            const payload = JSON.stringify({ name: values.name, email: values.email });
            /** @type {HTMLElement} */ (document.getElementById('result')).textContent = `Would send: ${payload}`;
            A11Y.announce('Account created', 'polite');
        },
        (errors) => {
            /** @type {HTMLElement} */ (document.getElementById('result')).textContent = '';
            showErrors(errors);
        },
    );
}

element.addEventListener('submit', (event) => {
    event.preventDefault();
    submit();
});

index.html

htmlApache-2.039 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · A sign-up form with accessible validation</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>A sign-up form with accessible validation</h1>
    <form id="signup" novalidate>
      <p>
        <label for="name">Name</label>
        <input id="name" name="name" type="text" autocomplete="name">
        <span id="name-error" class="error"></span>
      </p>
      <p>
        <label for="email">Email</label>
        <input id="email" name="email" type="email" autocomplete="email">
        <span id="email-error" class="error"></span>
      </p>
      <p>
        <label for="password">Password (8 characters or more)</label>
        <input id="password" name="password" type="password" autocomplete="new-password">
        <span id="password-error" class="error"></span>
      </p>
      <button type="submit">Create account</button>
    </form>
    <p id="result" aria-live="polite"></p>
  </main>
</body>
</html>