A routed contact form with accessible validation
A routed contact form with accessible validation and a confirmation page; nothing is sent.
Apache-2.0Runs on this page
Package: @awacloud/fw
Two hash-routed views: a contact form validated from a schema with announced, linked errors, then a confirmation view rendered from a template with the payload that would be sent. Nothing is sent.
Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.
When to use it
The classic small page: a form people fill in, checked before anything
leaves the browser, and a confirmation they can come back to. Replace the
onValid callback with your fetch and keep everything else.
Copy-paste steps
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works). - Copy
index.html,main.jsandcontact.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. - Edit
SCHEMAand the fields in bothindex.htmlandcontact.js; send the payload from theonValidcallback inmain.js.
What it shows
How it fits together
- The form half comes from
fw/dom-form:formKitover avalidschema,a11y.aria/describedBy/announce, focus on the first invalid field; here it iscontact.js, a module that takes the resolved fw modules and the<form>and exposessubmit/reset. - The views come from
fw/dom-route:route.on,route.start,route.go, androute.replaceto bounce off the confirmation view while nothing was sent. - The confirmation comes from
fw/dom-template:parser.fromHTMLonce,render.partsper submission,template.elmsinto the view; the payload is bound as text, so it can hold anything. registerAllDeeppullsform,valid,reactiveBind,signal,dom,eventsandsecPolicyalong through the descriptors'deps.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { route } from '@awacloud/fw/dom/utils/route.js';
import { formKit } from '@awacloud/fw/dom/utils/formKit.js';
import { a11y } from '@awacloud/fw/dom/utils/a11y.js';
import { template } from '@awacloud/fw/dom/rendering/template.js';
import { parser } from '@awacloud/fw/dom/rendering/parser.js';
import { render } from '@awacloud/fw/dom/rendering/render.js';
import { createContactForm } from './contact.js';
// `formKit` brings `form`, `valid`, `reactiveBind` and `signal` through its deps.
fw.runtime.registerAllDeep([route, formKit, a11y, template, parser, render]);
export const ROUTE = fw.runtime.resolve('route');
const A11Y = fw.runtime.resolve('a11y');
const TPL = fw.runtime.resolve('template');
const PARSER = fw.runtime.resolve('parser');
const RENDER = fw.runtime.resolve('render');
/** The confirmation view is data through a template: nothing is concatenated into markup. */
const CONFIRMATION = PARSER.fromHTML(
'<div><p>Thank you, <b>#{name}</b>. This is what <i>would</i> be sent to the server:</p>'
+ '<pre>#{payload}</pre></div>',
);
TPL.init('confirmation', { to: '#confirmation', main: true });
/** @type {Record<string, string> | null} the last valid submission */
export let sent = null;
/** @param {Record<string, string>} values */
export function renderConfirmation(values) {
TPL.clearAll('confirmation');
const part = RENDER.parts(CONFIRMATION.template, { name: values.name, payload: JSON.stringify(values, null, 2) });
TPL.elms('confirmation', part.arr);
}
const views = {
form: /** @type {HTMLElement} */ (document.getElementById('view-form')),
sent: /** @type {HTMLElement} */ (document.getElementById('view-sent')),
};
/** @param {'form' | 'sent'} name */
function show(name) {
for (const [key, section] of Object.entries(views)) section.hidden = key !== name;
A11Y.announce(/** @type {HTMLElement} */ (views[name].querySelector('h2')).textContent ?? name, 'polite');
}
export const contact = createContactForm(
{ formKit: fw.runtime.resolve('formKit'), a11y: A11Y },
/** @type {HTMLFormElement} */ (document.getElementById('contact')),
(values) => {
sent = values;
renderConfirmation(values);
ROUTE.go('/sent');
},
);
/** @type {HTMLFormElement} */ (document.getElementById('contact')).addEventListener('submit', (event) => {
event.preventDefault();
contact.submit();
});
ROUTE.on('form', '/', () => show('form'));
ROUTE.on('sent', '/sent', () => {
if (!sent) { ROUTE.replace('/'); return; } // nothing to confirm yet: back to the form
show('sent');
});
ROUTE.start();index.html
<!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 routed contact 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 routed contact form with accessible validation</h1>
<nav aria-label="Views"><a href="#/">Form</a> · <a href="#/sent">Confirmation</a></nav>
<section id="view-form" aria-labelledby="form-title">
<h2 id="form-title">Contact us</h2>
<form id="contact" 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="message">Message</label> <textarea id="message" name="message" rows="4"></textarea>
<span id="message-error" class="error"></span></p>
<button type="submit">Send</button>
</form>
</section>
<section id="view-sent" aria-labelledby="sent-title" hidden>
<h2 id="sent-title">Confirmation</h2>
<div id="confirmation"></div>
<p><a href="#/">Back to the form</a></p>
</section>
</main>
</body>
</html>contact.js
// SPDX-License-Identifier: Apache-2.0
// The form half of the recipe: a formKit controller over a schema, errors
// rendered next to their fields and announced, focus moved to the first one.
// Pure with respect to the page: it takes the modules and the form element.
export const FIELDS = ['name', 'email', 'message'];
export const SCHEMA = {
type: 'object',
required: FIELDS,
properties: {
name: { type: 'string', minLength: 2, maxLength: 80 },
email: { type: 'string', format: 'email' },
message: { type: 'string', minLength: 10, maxLength: 2000 },
},
};
/**
* @param {{ formKit: any, a11y: any, focus?: any }} modules resolved fw modules
* @param {HTMLFormElement} element the `<form>` with one input per field and one `<span id="<field>-error">`
* @param {(values: Record<string, string>) => void} onValid
* @returns {{ submit: () => Promise<void>, showErrors: (errors: Record<string, string>) => string[],
* reset: () => void }}
*/
export function createContactForm({ formKit, a11y }, element, onValid) {
const fk = formKit.create({ schema: SCHEMA, defaultValues: Object.fromEntries(FIELDS.map((f) => [f, ''])) });
const input = (name) => /** @type {HTMLInputElement} */ (element.elements.namedItem(name));
for (const name of FIELDS) fk.form.attach(name, input(name));
/** @param {Record<string, string>} errors */
function showErrors(errors) {
const invalid = FIELDS.filter((name) => errors[name]);
for (const name of FIELDS) {
const message = errors[name] ?? '';
/** @type {HTMLElement} */ (element.querySelector(`#${name}-error`)).textContent = message;
a11y.aria(input(name), { invalid: message ? 'true' : null });
a11y.describedBy(input(name), message ? [`${name}-error`] : []);
}
if (invalid.length) {
input(invalid[0]).focus();
a11y.announce(`${invalid.length} field${invalid.length > 1 ? 's need' : ' needs'} attention`, 'assertive');
}
return invalid;
}
return {
submit: () => fk.submit((values) => { showErrors({}); onValid(values); }, showErrors),
showErrors,
reset: () => { fk.reset(); showErrors({}); },
};
}