Forms examples.
Twelve real forms, each driven by the published API, with HTML / CDN and Package / ESM files you can copy. The same previews appear on Home and in Docs.
Every preview is a labeled native form: invalid controls receive aria-invalid, messages are announced politely, and a failed submit moves focus to the first field to fix.
Check a sign-up form before it is sent
Check a sign-up form before it is sent
form(element, { autoValidate: false, validators })- Errors
- Submit attempts
- Submitted
Rules for required fields, email format, password strength and a matching confirmation. Messages appear after the first submit and update as you correct each field.
autoValidate: false keeps the form quiet until the first submit; after that every input revalidates, and focus moves to the first field that needs attention.
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Check a sign-up form before it is sent</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="signup" class="demo-form" novalidate aria-labelledby="signup-heading">
<h1 id="signup-heading">Check a sign-up form before it is sent</h1>
<div class="field">
<label for="signup-name">Full name</label>
<input
type="text"
id="signup-name"
name="name"
autocomplete="name"
aria-describedby="signup-name-error"
/>
<p class="error" id="signup-name-error" data-error-for="name" aria-live="polite"></p>
</div>
<div class="field">
<label for="signup-email">Email</label>
<input
type="email"
id="signup-email"
name="email"
autocomplete="email"
placeholder="name@example.com"
aria-describedby="signup-email-error"
/>
<p class="error" id="signup-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="signup-password">Password</label>
<input
type="password"
id="signup-password"
name="password"
autocomplete="new-password"
aria-describedby="signup-password-help signup-password-error"
/>
<p class="help" id="signup-password-help">At least 8 characters, including a number.</p>
<p
class="error"
id="signup-password-error"
data-error-for="password"
aria-live="polite"
></p>
</div>
<div class="field">
<label for="signup-password-confirmation">Confirm password</label>
<input
type="password"
id="signup-password-confirmation"
name="password_confirmation"
autocomplete="new-password"
aria-describedby="signup-password-confirmation-error"
/>
<p
class="error"
id="signup-password-confirmation-error"
data-error-for="password_confirmation"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Create account</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Errors</dt>
<dd><output data-readout="errors">—</output></dd>
<dt>Submit attempts</dt>
<dd><output data-readout="attempts">—</output></dd>
<dt>Submitted</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const signup = (element, show) => {
const controller = form(element, {
// Stay quiet until the first submit, then revalidate on every input.
autoValidate: false,
validators: {
name: { required: { value: true, message: 'Tell us your name.' } },
email: {
required: { value: true, message: 'Enter your email address.' },
pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Use a valid email address.' },
},
password: {
required: { value: true, message: 'Choose a password.' },
minLength: { value: 8, message: 'Use at least 8 characters.' },
pattern: { value: /\d/, message: 'Include at least one number.' },
},
password_confirmation: {
required: { value: true, message: 'Repeat the password.' },
sameAs: { value: 'password', message: 'The passwords do not match.' },
},
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
const count = Object.keys(state.errors).length
show('errors', count === 0 ? 'None' : `${count} field${count === 1 ? '' : 's'} to fix`)
show('attempts', String(state.submitCount))
})
controller.onSubmit((_element, data) => {
show('result', `Account ready for ${data.email}`)
})
return controller
}
const element = document.querySelector('#signup')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = signup(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Check a sign-up form before it is sent</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="signup" class="demo-form" novalidate aria-labelledby="signup-heading">
<h1 id="signup-heading">Check a sign-up form before it is sent</h1>
<div class="field">
<label for="signup-name">Full name</label>
<input
type="text"
id="signup-name"
name="name"
autocomplete="name"
aria-describedby="signup-name-error"
/>
<p class="error" id="signup-name-error" data-error-for="name" aria-live="polite"></p>
</div>
<div class="field">
<label for="signup-email">Email</label>
<input
type="email"
id="signup-email"
name="email"
autocomplete="email"
placeholder="name@example.com"
aria-describedby="signup-email-error"
/>
<p class="error" id="signup-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="signup-password">Password</label>
<input
type="password"
id="signup-password"
name="password"
autocomplete="new-password"
aria-describedby="signup-password-help signup-password-error"
/>
<p class="help" id="signup-password-help">At least 8 characters, including a number.</p>
<p
class="error"
id="signup-password-error"
data-error-for="password"
aria-live="polite"
></p>
</div>
<div class="field">
<label for="signup-password-confirmation">Confirm password</label>
<input
type="password"
id="signup-password-confirmation"
name="password_confirmation"
autocomplete="new-password"
aria-describedby="signup-password-confirmation-error"
/>
<p
class="error"
id="signup-password-confirmation-error"
data-error-for="password_confirmation"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Create account</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Errors</dt>
<dd><output data-readout="errors">—</output></dd>
<dt>Submit attempts</dt>
<dd><output data-readout="attempts">—</output></dd>
<dt>Submitted</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const signup = (element, show) => {
const controller = form(element, {
// Stay quiet until the first submit, then revalidate on every input.
autoValidate: false,
validators: {
name: { required: { value: true, message: 'Tell us your name.' } },
email: {
required: { value: true, message: 'Enter your email address.' },
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: 'Use a valid email address.',
},
},
password: {
required: { value: true, message: 'Choose a password.' },
minLength: { value: 8, message: 'Use at least 8 characters.' },
pattern: { value: /\d/, message: 'Include at least one number.' },
},
password_confirmation: {
required: { value: true, message: 'Repeat the password.' },
sameAs: { value: 'password', message: 'The passwords do not match.' },
},
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
const count = Object.keys(state.errors).length
show('errors', count === 0 ? 'None' : `${count} field${count === 1 ? '' : 's'} to fix`)
show('attempts', String(state.submitCount))
})
controller.onSubmit((_element, data) => {
show('result', `Account ready for ${data.email}`)
})
return controller
}
const element = document.querySelector('#signup')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = signup(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Check a sign-up form before it is sent</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="signup" class="demo-form" novalidate aria-labelledby="signup-heading">
<h1 id="signup-heading">Check a sign-up form before it is sent</h1>
<div class="field">
<label for="signup-name">Full name</label>
<input
type="text"
id="signup-name"
name="name"
autocomplete="name"
aria-describedby="signup-name-error"
/>
<p class="error" id="signup-name-error" data-error-for="name" aria-live="polite"></p>
</div>
<div class="field">
<label for="signup-email">Email</label>
<input
type="email"
id="signup-email"
name="email"
autocomplete="email"
placeholder="name@example.com"
aria-describedby="signup-email-error"
/>
<p class="error" id="signup-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="signup-password">Password</label>
<input
type="password"
id="signup-password"
name="password"
autocomplete="new-password"
aria-describedby="signup-password-help signup-password-error"
/>
<p class="help" id="signup-password-help">At least 8 characters, including a number.</p>
<p
class="error"
id="signup-password-error"
data-error-for="password"
aria-live="polite"
></p>
</div>
<div class="field">
<label for="signup-password-confirmation">Confirm password</label>
<input
type="password"
id="signup-password-confirmation"
name="password_confirmation"
autocomplete="new-password"
aria-describedby="signup-password-confirmation-error"
/>
<p
class="error"
id="signup-password-confirmation-error"
data-error-for="password_confirmation"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Create account</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Errors</dt>
<dd><output data-readout="errors">—</output></dd>
<dt>Submit attempts</dt>
<dd><output data-readout="attempts">—</output></dd>
<dt>Submitted</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const signup = (element, show) => {
const controller = form(element, {
// Stay quiet until the first submit, then revalidate on every input.
autoValidate: false,
validators: {
name: { required: { value: true, message: 'Tell us your name.' } },
email: {
required: { value: true, message: 'Enter your email address.' },
pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Use a valid email address.' },
},
password: {
required: { value: true, message: 'Choose a password.' },
minLength: { value: 8, message: 'Use at least 8 characters.' },
pattern: { value: /\d/, message: 'Include at least one number.' },
},
password_confirmation: {
required: { value: true, message: 'Repeat the password.' },
sameAs: { value: 'password', message: 'The passwords do not match.' },
},
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
const count = Object.keys(state.errors).length
show('errors', count === 0 ? 'None' : `${count} field${count === 1 ? '' : 's'} to fix`)
show('attempts', String(state.submitCount))
})
controller.onSubmit((_element, data) => {
show('result', `Account ready for ${data.email}`)
})
return controller
}
const element = document.querySelector('#signup')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = signup(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Check a sign-up form before it is sent</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="signup" class="demo-form" novalidate aria-labelledby="signup-heading">
<h1 id="signup-heading">Check a sign-up form before it is sent</h1>
<div class="field">
<label for="signup-name">Full name</label>
<input
type="text"
id="signup-name"
name="name"
autocomplete="name"
aria-describedby="signup-name-error"
/>
<p class="error" id="signup-name-error" data-error-for="name" aria-live="polite"></p>
</div>
<div class="field">
<label for="signup-email">Email</label>
<input
type="email"
id="signup-email"
name="email"
autocomplete="email"
placeholder="name@example.com"
aria-describedby="signup-email-error"
/>
<p class="error" id="signup-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="signup-password">Password</label>
<input
type="password"
id="signup-password"
name="password"
autocomplete="new-password"
aria-describedby="signup-password-help signup-password-error"
/>
<p class="help" id="signup-password-help">At least 8 characters, including a number.</p>
<p
class="error"
id="signup-password-error"
data-error-for="password"
aria-live="polite"
></p>
</div>
<div class="field">
<label for="signup-password-confirmation">Confirm password</label>
<input
type="password"
id="signup-password-confirmation"
name="password_confirmation"
autocomplete="new-password"
aria-describedby="signup-password-confirmation-error"
/>
<p
class="error"
id="signup-password-confirmation-error"
data-error-for="password_confirmation"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Create account</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Errors</dt>
<dd><output data-readout="errors">—</output></dd>
<dt>Submit attempts</dt>
<dd><output data-readout="attempts">—</output></dd>
<dt>Submitted</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const signup = (element, show) => {
const controller = form(element, {
// Stay quiet until the first submit, then revalidate on every input.
autoValidate: false,
validators: {
name: { required: { value: true, message: 'Tell us your name.' } },
email: {
required: { value: true, message: 'Enter your email address.' },
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: 'Use a valid email address.',
},
},
password: {
required: { value: true, message: 'Choose a password.' },
minLength: { value: 8, message: 'Use at least 8 characters.' },
pattern: { value: /\d/, message: 'Include at least one number.' },
},
password_confirmation: {
required: { value: true, message: 'Repeat the password.' },
sameAs: { value: 'password', message: 'The passwords do not match.' },
},
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
const count = Object.keys(state.errors).length
show('errors', count === 0 ? 'None' : `${count} field${count === 1 ? '' : 's'} to fix`)
show('attempts', String(state.submitCount))
})
controller.onSubmit((_element, data) => {
show('result', `Account ready for ${data.email}`)
})
return controller
}
const element = document.querySelector('#signup')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = signup(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Format phone, card and amount fields while sending clean values
Format phone, card and amount fields while sending clean values
form(element, { formats: { phone: { type: 'phone', field: 'phone' } } })- phone sent
- card sent
- amount sent
Type freely: each field formats as you go, and the submitted data keeps the digits your backend expects under the original field name.
Formatting uses the optional peer @samline/formatter. The visible input is renamed to <name>_displayed and a hidden input keeps <name> with the raw value.
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Format phone, card and amount fields while sending clean values</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="checkout" class="demo-form" novalidate aria-labelledby="checkout-heading">
<h1 id="checkout-heading">
Format phone, card and amount fields while sending clean values
</h1>
<div class="field">
<label for="checkout-phone">Phone (US)</label>
<input
type="tel"
id="checkout-phone"
name="phone"
autocomplete="tel-national"
inputmode="tel"
placeholder="(202) 555-0123"
/>
</div>
<div class="field">
<label for="checkout-card">Card number</label>
<input
type="text"
id="checkout-card"
name="card"
autocomplete="cc-number"
inputmode="numeric"
placeholder="4111 1111 1111 1111"
/>
</div>
<div class="field">
<label for="checkout-amount">Amount</label>
<input
type="text"
id="checkout-amount"
name="amount"
inputmode="decimal"
placeholder="1,250.00"
/>
</div>
<div class="actions">
<button type="submit">Review payment</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>phone sent</dt>
<dd><output data-readout="phone">—</output></dd>
<dt>card sent</dt>
<dd><output data-readout="card">—</output></dd>
<dt>amount sent</dt>
<dd><output data-readout="amount">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
const checkout = (element, show) => {
const controller = form(element, {
// Each visible input keeps its formatting; a hidden input with the
// original name carries the clean value that is submitted.
formats: {
phone: { type: 'phone', field: 'phone', options: { country: 'US' } },
card: { type: 'creditCard', field: 'card' },
amount: { type: 'numeral', field: 'amount' },
},
})
const update = () => {
const { data } = controller.getData()
show('phone', data.phone || '—')
show('card', data.card || '—')
show('amount', data.amount || '—')
}
controller.subscribe(update)
controller.onSubmit(update)
return controller
}
const element = document.querySelector('#checkout')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = checkout(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Format phone, card and amount fields while sending clean values</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="checkout" class="demo-form" novalidate aria-labelledby="checkout-heading">
<h1 id="checkout-heading">
Format phone, card and amount fields while sending clean values
</h1>
<div class="field">
<label for="checkout-phone">Phone (US)</label>
<input
type="tel"
id="checkout-phone"
name="phone"
autocomplete="tel-national"
inputmode="tel"
placeholder="(202) 555-0123"
/>
</div>
<div class="field">
<label for="checkout-card">Card number</label>
<input
type="text"
id="checkout-card"
name="card"
autocomplete="cc-number"
inputmode="numeric"
placeholder="4111 1111 1111 1111"
/>
</div>
<div class="field">
<label for="checkout-amount">Amount</label>
<input
type="text"
id="checkout-amount"
name="amount"
inputmode="decimal"
placeholder="1,250.00"
/>
</div>
<div class="actions">
<button type="submit">Review payment</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>phone sent</dt>
<dd><output data-readout="phone">—</output></dd>
<dt>card sent</dt>
<dd><output data-readout="card">—</output></dd>
<dt>amount sent</dt>
<dd><output data-readout="amount">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
const checkout = (element, show) => {
const controller = form(element, {
// Each visible input keeps its formatting; a hidden input with the
// original name carries the clean value that is submitted.
formats: {
phone: { type: 'phone', field: 'phone', options: { country: 'US' } },
card: { type: 'creditCard', field: 'card' },
amount: { type: 'numeral', field: 'amount' },
},
})
const update = () => {
const { data } = controller.getData()
show('phone', data.phone || '—')
show('card', data.card || '—')
show('amount', data.amount || '—')
}
controller.subscribe(update)
controller.onSubmit(update)
return controller
}
const element = document.querySelector('#checkout')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = checkout(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Format phone, card and amount fields while sending clean values</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="checkout" class="demo-form" novalidate aria-labelledby="checkout-heading">
<h1 id="checkout-heading">
Format phone, card and amount fields while sending clean values
</h1>
<div class="field">
<label for="checkout-phone">Phone (US)</label>
<input
type="tel"
id="checkout-phone"
name="phone"
autocomplete="tel-national"
inputmode="tel"
placeholder="(202) 555-0123"
/>
</div>
<div class="field">
<label for="checkout-card">Card number</label>
<input
type="text"
id="checkout-card"
name="card"
autocomplete="cc-number"
inputmode="numeric"
placeholder="4111 1111 1111 1111"
/>
</div>
<div class="field">
<label for="checkout-amount">Amount</label>
<input
type="text"
id="checkout-amount"
name="amount"
inputmode="decimal"
placeholder="1,250.00"
/>
</div>
<div class="actions">
<button type="submit">Review payment</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>phone sent</dt>
<dd><output data-readout="phone">—</output></dd>
<dt>card sent</dt>
<dd><output data-readout="card">—</output></dd>
<dt>amount sent</dt>
<dd><output data-readout="amount">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
const checkout = (element, show) => {
const controller = form(element, {
// Each visible input keeps its formatting; a hidden input with the
// original name carries the clean value that is submitted.
formats: {
phone: { type: 'phone', field: 'phone', options: { country: 'US' } },
card: { type: 'creditCard', field: 'card' },
amount: { type: 'numeral', field: 'amount' },
},
})
const update = () => {
const { data } = controller.getData()
show('phone', data.phone || '—')
show('card', data.card || '—')
show('amount', data.amount || '—')
}
controller.subscribe(update)
controller.onSubmit(update)
return controller
}
const element = document.querySelector('#checkout')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = checkout(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Format phone, card and amount fields while sending clean values</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="checkout" class="demo-form" novalidate aria-labelledby="checkout-heading">
<h1 id="checkout-heading">
Format phone, card and amount fields while sending clean values
</h1>
<div class="field">
<label for="checkout-phone">Phone (US)</label>
<input
type="tel"
id="checkout-phone"
name="phone"
autocomplete="tel-national"
inputmode="tel"
placeholder="(202) 555-0123"
/>
</div>
<div class="field">
<label for="checkout-card">Card number</label>
<input
type="text"
id="checkout-card"
name="card"
autocomplete="cc-number"
inputmode="numeric"
placeholder="4111 1111 1111 1111"
/>
</div>
<div class="field">
<label for="checkout-amount">Amount</label>
<input
type="text"
id="checkout-amount"
name="amount"
inputmode="decimal"
placeholder="1,250.00"
/>
</div>
<div class="actions">
<button type="submit">Review payment</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>phone sent</dt>
<dd><output data-readout="phone">—</output></dd>
<dt>card sent</dt>
<dd><output data-readout="card">—</output></dd>
<dt>amount sent</dt>
<dd><output data-readout="amount">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
const checkout = (element, show) => {
const controller = form(element, {
// Each visible input keeps its formatting; a hidden input with the
// original name carries the clean value that is submitted.
formats: {
phone: { type: 'phone', field: 'phone', options: { country: 'US' } },
card: { type: 'creditCard', field: 'card' },
amount: { type: 'numeral', field: 'amount' },
},
})
const update = () => {
const { data } = controller.getData()
show('phone', data.phone || '—')
show('card', data.card || '—')
show('amount', data.amount || '—')
}
controller.subscribe(update)
controller.onSubmit(update)
return controller
}
const element = document.querySelector('#checkout')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = checkout(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Filter a catalog as soon as the visitor changes an option
Filter a catalog as soon as the visitor changes an option
form(element, { autoSubmit: { debounce: 250 } }).prefill()- Query string
- Results
Search, a category and tag checkboxes submit themselves after a short pause. The handler receives FormData, so building the query string is one line.
Repeated names such as tags[] arrive as arrays. prefill() restores the same filters from a shared link, for example ?category=decor&tags[]=sale.
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Filter a catalog as soon as the visitor changes an option</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="filters" class="demo-form" novalidate aria-labelledby="filters-heading">
<h1 id="filters-heading">Filter a catalog as soon as the visitor changes an option</h1>
<div class="field">
<label for="filters-q">Search</label>
<input
type="search"
id="filters-q"
name="q"
autocomplete="off"
placeholder="Lamp, table, vase…"
/>
</div>
<div class="field">
<label for="filters-category">Category</label>
<select id="filters-category" name="category">
<option value="">All categories</option>
<option value="lighting">Lighting</option>
<option value="furniture">Furniture</option>
<option value="decor">Decor</option>
</select>
</div>
<fieldset class="field">
<legend>Only show</legend>
<label class="check"
><input type="checkbox" name="tags[]" value="new" /> New arrivals</label
>
<label class="check"><input type="checkbox" name="tags[]" value="sale" /> On sale</label>
</fieldset>
<div class="actions">
<button type="submit">Apply filters</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Query string</dt>
<dd><output data-readout="query">—</output></dd>
<dt>Results</dt>
<dd><output data-readout="results">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
const catalog = [
{ name: 'Arc floor lamp', category: 'lighting', tags: ['sale'] },
{ name: 'Linen desk lamp', category: 'lighting', tags: ['new'] },
{ name: 'Oak side table', category: 'furniture', tags: ['new', 'sale'] },
{ name: 'Wool lounge chair', category: 'furniture', tags: [] },
{ name: 'Stoneware vase', category: 'decor', tags: ['sale'] },
{ name: 'Woven wall hanging', category: 'decor', tags: ['new'] },
]
const filters = (element, show) => {
const controller = form(element, { autoSubmit: { debounce: 250 } })
controller.onSubmit((_element, data, formData) => {
const query = String(data.q ?? '')
.trim()
.toLowerCase()
const tags = formData.getAll('tags[]')
const matches = catalog.filter(
item =>
item.name.toLowerCase().includes(query) &&
(!data.category || item.category === data.category) &&
tags.every(tag => item.tags.includes(tag))
)
show('query', `?${new URLSearchParams(formData)}`)
show('results', matches.map(item => item.name).join(', ') || 'No matching products')
})
// Restore filters from a shared link such as ?category=decor&tags[]=sale.
controller.prefill()
element.requestSubmit()
return controller
}
const element = document.querySelector('#filters')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = filters(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Filter a catalog as soon as the visitor changes an option</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="filters" class="demo-form" novalidate aria-labelledby="filters-heading">
<h1 id="filters-heading">Filter a catalog as soon as the visitor changes an option</h1>
<div class="field">
<label for="filters-q">Search</label>
<input
type="search"
id="filters-q"
name="q"
autocomplete="off"
placeholder="Lamp, table, vase…"
/>
</div>
<div class="field">
<label for="filters-category">Category</label>
<select id="filters-category" name="category">
<option value="">All categories</option>
<option value="lighting">Lighting</option>
<option value="furniture">Furniture</option>
<option value="decor">Decor</option>
</select>
</div>
<fieldset class="field">
<legend>Only show</legend>
<label class="check"
><input type="checkbox" name="tags[]" value="new" /> New arrivals</label
>
<label class="check"><input type="checkbox" name="tags[]" value="sale" /> On sale</label>
</fieldset>
<div class="actions">
<button type="submit">Apply filters</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Query string</dt>
<dd><output data-readout="query">—</output></dd>
<dt>Results</dt>
<dd><output data-readout="results">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
const catalog = [
{ name: 'Arc floor lamp', category: 'lighting', tags: ['sale'] },
{ name: 'Linen desk lamp', category: 'lighting', tags: ['new'] },
{ name: 'Oak side table', category: 'furniture', tags: ['new', 'sale'] },
{ name: 'Wool lounge chair', category: 'furniture', tags: [] },
{ name: 'Stoneware vase', category: 'decor', tags: ['sale'] },
{ name: 'Woven wall hanging', category: 'decor', tags: ['new'] },
]
const filters = (element, show) => {
const controller = form(element, { autoSubmit: { debounce: 250 } })
controller.onSubmit((_element, data, formData) => {
const query = String(data.q ?? '')
.trim()
.toLowerCase()
const tags = formData.getAll('tags[]')
const matches = catalog.filter(
item =>
item.name.toLowerCase().includes(query) &&
(!data.category || item.category === data.category) &&
tags.every(tag => item.tags.includes(tag))
)
show('query', `?${new URLSearchParams(formData)}`)
show('results', matches.map(item => item.name).join(', ') || 'No matching products')
})
// Restore filters from a shared link such as ?category=decor&tags[]=sale.
controller.prefill()
element.requestSubmit()
return controller
}
const element = document.querySelector('#filters')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = filters(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Filter a catalog as soon as the visitor changes an option</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="filters" class="demo-form" novalidate aria-labelledby="filters-heading">
<h1 id="filters-heading">Filter a catalog as soon as the visitor changes an option</h1>
<div class="field">
<label for="filters-q">Search</label>
<input
type="search"
id="filters-q"
name="q"
autocomplete="off"
placeholder="Lamp, table, vase…"
/>
</div>
<div class="field">
<label for="filters-category">Category</label>
<select id="filters-category" name="category">
<option value="">All categories</option>
<option value="lighting">Lighting</option>
<option value="furniture">Furniture</option>
<option value="decor">Decor</option>
</select>
</div>
<fieldset class="field">
<legend>Only show</legend>
<label class="check"
><input type="checkbox" name="tags[]" value="new" /> New arrivals</label
>
<label class="check"><input type="checkbox" name="tags[]" value="sale" /> On sale</label>
</fieldset>
<div class="actions">
<button type="submit">Apply filters</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Query string</dt>
<dd><output data-readout="query">—</output></dd>
<dt>Results</dt>
<dd><output data-readout="results">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
const catalog = [
{ name: 'Arc floor lamp', category: 'lighting', tags: ['sale'] },
{ name: 'Linen desk lamp', category: 'lighting', tags: ['new'] },
{ name: 'Oak side table', category: 'furniture', tags: ['new', 'sale'] },
{ name: 'Wool lounge chair', category: 'furniture', tags: [] },
{ name: 'Stoneware vase', category: 'decor', tags: ['sale'] },
{ name: 'Woven wall hanging', category: 'decor', tags: ['new'] },
]
const filters = (element, show) => {
const controller = form(element, { autoSubmit: { debounce: 250 } })
controller.onSubmit((_element, data, formData) => {
const query = String(data.q ?? '')
.trim()
.toLowerCase()
const tags = formData.getAll('tags[]')
const matches = catalog.filter(
item =>
item.name.toLowerCase().includes(query) &&
(!data.category || item.category === data.category) &&
tags.every(tag => item.tags.includes(tag))
)
show('query', `?${new URLSearchParams(formData)}`)
show('results', matches.map(item => item.name).join(', ') || 'No matching products')
})
// Restore filters from a shared link such as ?category=decor&tags[]=sale.
controller.prefill()
element.requestSubmit()
return controller
}
const element = document.querySelector('#filters')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = filters(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Filter a catalog as soon as the visitor changes an option</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="filters" class="demo-form" novalidate aria-labelledby="filters-heading">
<h1 id="filters-heading">Filter a catalog as soon as the visitor changes an option</h1>
<div class="field">
<label for="filters-q">Search</label>
<input
type="search"
id="filters-q"
name="q"
autocomplete="off"
placeholder="Lamp, table, vase…"
/>
</div>
<div class="field">
<label for="filters-category">Category</label>
<select id="filters-category" name="category">
<option value="">All categories</option>
<option value="lighting">Lighting</option>
<option value="furniture">Furniture</option>
<option value="decor">Decor</option>
</select>
</div>
<fieldset class="field">
<legend>Only show</legend>
<label class="check"
><input type="checkbox" name="tags[]" value="new" /> New arrivals</label
>
<label class="check"><input type="checkbox" name="tags[]" value="sale" /> On sale</label>
</fieldset>
<div class="actions">
<button type="submit">Apply filters</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Query string</dt>
<dd><output data-readout="query">—</output></dd>
<dt>Results</dt>
<dd><output data-readout="results">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
const catalog = [
{ name: 'Arc floor lamp', category: 'lighting', tags: ['sale'] },
{ name: 'Linen desk lamp', category: 'lighting', tags: ['new'] },
{ name: 'Oak side table', category: 'furniture', tags: ['new', 'sale'] },
{ name: 'Wool lounge chair', category: 'furniture', tags: [] },
{ name: 'Stoneware vase', category: 'decor', tags: ['sale'] },
{ name: 'Woven wall hanging', category: 'decor', tags: ['new'] },
]
const filters = (element, show) => {
const controller = form(element, { autoSubmit: { debounce: 250 } })
controller.onSubmit((_element, data, formData) => {
const query = String(data.q ?? '')
.trim()
.toLowerCase()
const tags = formData.getAll('tags[]')
const matches = catalog.filter(
item =>
item.name.toLowerCase().includes(query) &&
(!data.category || item.category === data.category) &&
tags.every(tag => item.tags.includes(tag))
)
show('query', `?${new URLSearchParams(formData)}`)
show('results', matches.map(item => item.name).join(', ') || 'No matching products')
})
// Restore filters from a shared link such as ?category=decor&tags[]=sale.
controller.prefill()
element.requestSubmit()
return controller
}
const element = document.querySelector('#filters')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = filters(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Enable the send button only when the message is ready
Enable the send button only when the message is ready
controller.subscribe(state => (button.disabled = !state.isValid))- Status
- Filled fields
- Characters
A subscriber receives every state change: it counts characters, lists the fields you filled and enables the button once every rule passes.
Rules run on load, so errors exist from the start. The subscriber prints only those of filled fields (state.filledFields), and the CSS highlights [css-error][css-filled] controls.
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Enable the send button only when the message is ready</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form
id="feedback"
class="demo-form"
data-errors="filled"
novalidate
aria-labelledby="feedback-heading"
>
<h1 id="feedback-heading">Enable the send button only when the message is ready</h1>
<div class="field">
<label for="feedback-email">Reply to</label>
<input
type="email"
id="feedback-email"
name="email"
autocomplete="email"
placeholder="name@example.com"
aria-describedby="feedback-email-error"
/>
<p class="error" id="feedback-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="feedback-message">Message</label>
<textarea
id="feedback-message"
name="message"
placeholder="What should we improve?"
aria-describedby="feedback-message-error"
rows="4"
></textarea>
<p
class="error"
id="feedback-message-error"
data-error-for="message"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Send feedback</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Status</dt>
<dd><output data-readout="valid">—</output></dd>
<dt>Filled fields</dt>
<dd><output data-readout="filled">—</output></dd>
<dt>Characters</dt>
<dd><output data-readout="characters">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const feedback = (element, show) => {
const button = element.querySelector('button[type="submit"]')
const controller = form(element, {
validators: {
email: {
required: { value: true, message: 'Enter an email we can reply to.' },
pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Use a valid email address.' },
},
message: {
required: { value: true, message: 'Write a message.' },
minLength: { value: 20, message: 'Add a little more detail (20 characters).' },
maxLength: { value: 140, message: 'Keep it under 140 characters.' },
},
},
})
controller.observe('message', value => {
show('characters', `${String(value ?? '').length} / 140`)
})
controller.subscribe(state => {
// Only fields the visitor has filled show their messages.
const visible = Object.fromEntries(
Object.entries(state.errors).filter(([name]) => state.filledFields.includes(name))
)
renderErrors(element, visible)
button.disabled = !state.isValid
show('valid', state.isValid ? 'Ready to send' : 'Not yet')
show('filled', state.filledFields.join(', ') || 'None')
})
controller.onSubmit(() => {
controller.reset()
show('valid', 'Sent (local demo, nothing left the page)')
})
return controller
}
const element = document.querySelector('#feedback')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = feedback(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Enable the send button only when the message is ready</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form
id="feedback"
class="demo-form"
data-errors="filled"
novalidate
aria-labelledby="feedback-heading"
>
<h1 id="feedback-heading">Enable the send button only when the message is ready</h1>
<div class="field">
<label for="feedback-email">Reply to</label>
<input
type="email"
id="feedback-email"
name="email"
autocomplete="email"
placeholder="name@example.com"
aria-describedby="feedback-email-error"
/>
<p class="error" id="feedback-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="feedback-message">Message</label>
<textarea
id="feedback-message"
name="message"
placeholder="What should we improve?"
aria-describedby="feedback-message-error"
rows="4"
></textarea>
<p
class="error"
id="feedback-message-error"
data-error-for="message"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Send feedback</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Status</dt>
<dd><output data-readout="valid">—</output></dd>
<dt>Filled fields</dt>
<dd><output data-readout="filled">—</output></dd>
<dt>Characters</dt>
<dd><output data-readout="characters">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const feedback = (element, show) => {
const button = element.querySelector('button[type="submit"]')
const controller = form(element, {
validators: {
email: {
required: { value: true, message: 'Enter an email we can reply to.' },
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: 'Use a valid email address.',
},
},
message: {
required: { value: true, message: 'Write a message.' },
minLength: { value: 20, message: 'Add a little more detail (20 characters).' },
maxLength: { value: 140, message: 'Keep it under 140 characters.' },
},
},
})
controller.observe('message', value => {
show('characters', `${String(value ?? '').length} / 140`)
})
controller.subscribe(state => {
// Only fields the visitor has filled show their messages.
const visible = Object.fromEntries(
Object.entries(state.errors).filter(([name]) => state.filledFields.includes(name))
)
renderErrors(element, visible)
button.disabled = !state.isValid
show('valid', state.isValid ? 'Ready to send' : 'Not yet')
show('filled', state.filledFields.join(', ') || 'None')
})
controller.onSubmit(() => {
controller.reset()
show('valid', 'Sent (local demo, nothing left the page)')
})
return controller
}
const element = document.querySelector('#feedback')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = feedback(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Enable the send button only when the message is ready</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form
id="feedback"
class="demo-form"
data-errors="filled"
novalidate
aria-labelledby="feedback-heading"
>
<h1 id="feedback-heading">Enable the send button only when the message is ready</h1>
<div class="field">
<label for="feedback-email">Reply to</label>
<input
type="email"
id="feedback-email"
name="email"
autocomplete="email"
placeholder="name@example.com"
aria-describedby="feedback-email-error"
/>
<p class="error" id="feedback-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="feedback-message">Message</label>
<textarea
id="feedback-message"
name="message"
placeholder="What should we improve?"
aria-describedby="feedback-message-error"
rows="4"
></textarea>
<p
class="error"
id="feedback-message-error"
data-error-for="message"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Send feedback</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Status</dt>
<dd><output data-readout="valid">—</output></dd>
<dt>Filled fields</dt>
<dd><output data-readout="filled">—</output></dd>
<dt>Characters</dt>
<dd><output data-readout="characters">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const feedback = (element, show) => {
const button = element.querySelector('button[type="submit"]')
const controller = form(element, {
validators: {
email: {
required: { value: true, message: 'Enter an email we can reply to.' },
pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Use a valid email address.' },
},
message: {
required: { value: true, message: 'Write a message.' },
minLength: { value: 20, message: 'Add a little more detail (20 characters).' },
maxLength: { value: 140, message: 'Keep it under 140 characters.' },
},
},
})
controller.observe('message', value => {
show('characters', `${String(value ?? '').length} / 140`)
})
controller.subscribe(state => {
// Only fields the visitor has filled show their messages.
const visible = Object.fromEntries(
Object.entries(state.errors).filter(([name]) => state.filledFields.includes(name))
)
renderErrors(element, visible)
button.disabled = !state.isValid
show('valid', state.isValid ? 'Ready to send' : 'Not yet')
show('filled', state.filledFields.join(', ') || 'None')
})
controller.onSubmit(() => {
controller.reset()
show('valid', 'Sent (local demo, nothing left the page)')
})
return controller
}
const element = document.querySelector('#feedback')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = feedback(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Enable the send button only when the message is ready</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form
id="feedback"
class="demo-form"
data-errors="filled"
novalidate
aria-labelledby="feedback-heading"
>
<h1 id="feedback-heading">Enable the send button only when the message is ready</h1>
<div class="field">
<label for="feedback-email">Reply to</label>
<input
type="email"
id="feedback-email"
name="email"
autocomplete="email"
placeholder="name@example.com"
aria-describedby="feedback-email-error"
/>
<p class="error" id="feedback-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="feedback-message">Message</label>
<textarea
id="feedback-message"
name="message"
placeholder="What should we improve?"
aria-describedby="feedback-message-error"
rows="4"
></textarea>
<p
class="error"
id="feedback-message-error"
data-error-for="message"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Send feedback</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Status</dt>
<dd><output data-readout="valid">—</output></dd>
<dt>Filled fields</dt>
<dd><output data-readout="filled">—</output></dd>
<dt>Characters</dt>
<dd><output data-readout="characters">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const feedback = (element, show) => {
const button = element.querySelector('button[type="submit"]')
const controller = form(element, {
validators: {
email: {
required: { value: true, message: 'Enter an email we can reply to.' },
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: 'Use a valid email address.',
},
},
message: {
required: { value: true, message: 'Write a message.' },
minLength: { value: 20, message: 'Add a little more detail (20 characters).' },
maxLength: { value: 140, message: 'Keep it under 140 characters.' },
},
},
})
controller.observe('message', value => {
show('characters', `${String(value ?? '').length} / 140`)
})
controller.subscribe(state => {
// Only fields the visitor has filled show their messages.
const visible = Object.fromEntries(
Object.entries(state.errors).filter(([name]) => state.filledFields.includes(name))
)
renderErrors(element, visible)
button.disabled = !state.isValid
show('valid', state.isValid ? 'Ready to send' : 'Not yet')
show('filled', state.filledFields.join(', ') || 'None')
})
controller.onSubmit(() => {
controller.reset()
show('valid', 'Sent (local demo, nothing left the page)')
})
return controller
}
const element = document.querySelector('#feedback')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = feedback(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Show the server’s answer next to the field
Show the server’s answer next to the field
controller.setErrors({ username: ['That username is already taken.'] })- Server
The submit handler awaits a simulated availability check, then attaches the rejection to the username field with setErrors().
Local simulation: the “server” answers after 600 ms without any network request. Try admin, ada or support. A manual error clears as soon as the field changes.
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Show the server’s answer next to the field</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="username" class="demo-form" novalidate aria-labelledby="username-heading">
<h1 id="username-heading">Show the server’s answer next to the field</h1>
<div class="field">
<label for="username-username">Username</label>
<input
type="text"
id="username-username"
name="username"
autocomplete="username"
placeholder="ada_dev"
aria-describedby="username-username-error"
/>
<p
class="error"
id="username-username-error"
data-error-for="username"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Claim username</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Server</dt>
<dd><output data-readout="request">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const takenNames = ['admin', 'ada', 'support']
// Stands in for your API. It answers after 600 ms and never uses the network.
const checkAvailability = username =>
new Promise(resolve => {
setTimeout(() => resolve(!takenNames.includes(username.toLowerCase())), 600)
})
const username = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
username: {
required: { value: true, message: 'Pick a username.' },
pattern: { value: /^[a-z0-9_]{3,}$/i, message: 'Use 3+ letters, numbers or _.' },
},
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
if (state.isSubmitting) show('request', 'Checking availability…')
})
controller.onSubmit(async (_element, data) => {
const available = await checkAvailability(String(data.username))
if (available) {
show('request', `“${data.username}” is yours`)
} else {
// A manual error stays until the visitor edits the field.
controller.setErrors({ username: ['That username is already taken.'] })
show('request', 'The server rejected the username')
}
})
return controller
}
const element = document.querySelector('#username')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = username(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Show the server’s answer next to the field</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="username" class="demo-form" novalidate aria-labelledby="username-heading">
<h1 id="username-heading">Show the server’s answer next to the field</h1>
<div class="field">
<label for="username-username">Username</label>
<input
type="text"
id="username-username"
name="username"
autocomplete="username"
placeholder="ada_dev"
aria-describedby="username-username-error"
/>
<p
class="error"
id="username-username-error"
data-error-for="username"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Claim username</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Server</dt>
<dd><output data-readout="request">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const takenNames = ['admin', 'ada', 'support']
// Stands in for your API. It answers after 600 ms and never uses the network.
const checkAvailability = username =>
new Promise(resolve => {
setTimeout(() => resolve(!takenNames.includes(username.toLowerCase())), 600)
})
const username = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
username: {
required: { value: true, message: 'Pick a username.' },
pattern: { value: /^[a-z0-9_]{3,}$/i, message: 'Use 3+ letters, numbers or _.' },
},
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
if (state.isSubmitting) show('request', 'Checking availability…')
})
controller.onSubmit(async (_element, data) => {
const available = await checkAvailability(String(data.username))
if (available) {
show('request', `“${data.username}” is yours`)
} else {
// A manual error stays until the visitor edits the field.
controller.setErrors({ username: ['That username is already taken.'] })
show('request', 'The server rejected the username')
}
})
return controller
}
const element = document.querySelector('#username')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = username(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Show the server’s answer next to the field</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="username" class="demo-form" novalidate aria-labelledby="username-heading">
<h1 id="username-heading">Show the server’s answer next to the field</h1>
<div class="field">
<label for="username-username">Username</label>
<input
type="text"
id="username-username"
name="username"
autocomplete="username"
placeholder="ada_dev"
aria-describedby="username-username-error"
/>
<p
class="error"
id="username-username-error"
data-error-for="username"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Claim username</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Server</dt>
<dd><output data-readout="request">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const takenNames = ['admin', 'ada', 'support']
// Stands in for your API. It answers after 600 ms and never uses the network.
const checkAvailability = username =>
new Promise(resolve => {
setTimeout(() => resolve(!takenNames.includes(username.toLowerCase())), 600)
})
const username = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
username: {
required: { value: true, message: 'Pick a username.' },
pattern: { value: /^[a-z0-9_]{3,}$/i, message: 'Use 3+ letters, numbers or _.' },
},
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
if (state.isSubmitting) show('request', 'Checking availability…')
})
controller.onSubmit(async (_element, data) => {
const available = await checkAvailability(String(data.username))
if (available) {
show('request', `“${data.username}” is yours`)
} else {
// A manual error stays until the visitor edits the field.
controller.setErrors({ username: ['That username is already taken.'] })
show('request', 'The server rejected the username')
}
})
return controller
}
const element = document.querySelector('#username')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = username(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Show the server’s answer next to the field</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="username" class="demo-form" novalidate aria-labelledby="username-heading">
<h1 id="username-heading">Show the server’s answer next to the field</h1>
<div class="field">
<label for="username-username">Username</label>
<input
type="text"
id="username-username"
name="username"
autocomplete="username"
placeholder="ada_dev"
aria-describedby="username-username-error"
/>
<p
class="error"
id="username-username-error"
data-error-for="username"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Claim username</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Server</dt>
<dd><output data-readout="request">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const takenNames = ['admin', 'ada', 'support']
// Stands in for your API. It answers after 600 ms and never uses the network.
const checkAvailability = username =>
new Promise(resolve => {
setTimeout(() => resolve(!takenNames.includes(username.toLowerCase())), 600)
})
const username = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
username: {
required: { value: true, message: 'Pick a username.' },
pattern: { value: /^[a-z0-9_]{3,}$/i, message: 'Use 3+ letters, numbers or _.' },
},
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
if (state.isSubmitting) show('request', 'Checking availability…')
})
controller.onSubmit(async (_element, data) => {
const available = await checkAvailability(String(data.username))
if (available) {
show('request', `“${data.username}” is yours`)
} else {
// A manual error stays until the visitor edits the field.
controller.setErrors({ username: ['That username is already taken.'] })
show('request', 'The server rejected the username')
}
})
return controller
}
const element = document.querySelector('#username')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = username(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Collect a guest list that grows one row at a time
Collect a guest list that grows one row at a time
validators: { 'guests[]': { each: { required: true } } }- Guests
- First error
Add or remove rows freely; the controller notices new inputs, reads guests[] as a list and marks only the row that is still empty.
Rules under each run once per input with the same name. addCleanup() removes the row buttons’ listener when the controller is destroyed.
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Collect a guest list that grows one row at a time</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="guests" class="demo-form" novalidate aria-labelledby="guests-heading">
<h1 id="guests-heading">Collect a guest list that grows one row at a time</h1>
<div class="guests" data-guests>
<div class="field" data-guest>
<label for="guest-1">Guest 1</label>
<div class="row">
<input id="guest-1" name="guests[]" autocomplete="off" />
<button type="button" data-remove>Remove</button>
</div>
</div>
</div>
<div class="actions">
<button type="button" data-add>Add guest</button>
<button type="submit">Send invitations</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Guests</dt>
<dd><output data-readout="guests">—</output></dd>
<dt>First error</dt>
<dd><output data-readout="errors">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
const guests = (element, show) => {
const list = element.querySelector('[data-guests]')
const template = list.querySelector('[data-guest]').cloneNode(true)
const controller = form(element, {
autoValidate: false,
validators: {
'guests[]': {
// `each` checks every row on its own, so only the empty row is marked.
each: { required: { value: true, message: 'Enter a name or remove the empty row.' } },
},
},
})
const renumber = () => {
list.querySelectorAll('[data-guest]').forEach((row, index) => {
const input = row.querySelector('input')
input.id = `guest-${index + 1}`
row.querySelector('label').htmlFor = input.id
row.querySelector('label').textContent = `Guest ${index + 1}`
})
}
const onClick = event => {
const target = event.target.closest('button')
if (target?.matches('[data-add]')) {
const row = template.cloneNode(true)
list.append(row)
renumber()
row.querySelector('input').focus()
} else if (target?.matches('[data-remove]') && list.children.length > 1) {
target.closest('[data-guest]').remove()
renumber()
}
}
element.addEventListener('click', onClick)
// destroy() runs registered cleanups, so the row buttons stop with the form.
controller.addCleanup(() => element.removeEventListener('click', onClick))
controller.subscribe(state => {
const names = [state.values['guests[]'] ?? []].flat().filter(Boolean)
show('guests', names.join(', ') || 'Nobody yet')
show('errors', state.errors['guests[]']?.[0] ?? 'None')
})
controller.onSubmit((_element, _data, formData) => {
const count = formData.getAll('guests[]').length
show('guests', `${count} invitation${count === 1 ? '' : 's'} ready`)
})
return controller
}
const element = document.querySelector('#guests')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = guests(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Collect a guest list that grows one row at a time</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="guests" class="demo-form" novalidate aria-labelledby="guests-heading">
<h1 id="guests-heading">Collect a guest list that grows one row at a time</h1>
<div class="guests" data-guests>
<div class="field" data-guest>
<label for="guest-1">Guest 1</label>
<div class="row">
<input id="guest-1" name="guests[]" autocomplete="off" />
<button type="button" data-remove>Remove</button>
</div>
</div>
</div>
<div class="actions">
<button type="button" data-add>Add guest</button>
<button type="submit">Send invitations</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Guests</dt>
<dd><output data-readout="guests">—</output></dd>
<dt>First error</dt>
<dd><output data-readout="errors">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
const guests = (element, show) => {
const list = element.querySelector('[data-guests]')
const template = list.querySelector('[data-guest]').cloneNode(true)
const controller = form(element, {
autoValidate: false,
validators: {
'guests[]': {
// `each` checks every row on its own, so only the empty row is marked.
each: { required: { value: true, message: 'Enter a name or remove the empty row.' } },
},
},
})
const renumber = () => {
list.querySelectorAll('[data-guest]').forEach((row, index) => {
const input = row.querySelector('input')
input.id = `guest-${index + 1}`
row.querySelector('label').htmlFor = input.id
row.querySelector('label').textContent = `Guest ${index + 1}`
})
}
const onClick = event => {
const target = event.target.closest('button')
if (target?.matches('[data-add]')) {
const row = template.cloneNode(true)
list.append(row)
renumber()
row.querySelector('input').focus()
} else if (target?.matches('[data-remove]') && list.children.length > 1) {
target.closest('[data-guest]').remove()
renumber()
}
}
element.addEventListener('click', onClick)
// destroy() runs registered cleanups, so the row buttons stop with the form.
controller.addCleanup(() => element.removeEventListener('click', onClick))
controller.subscribe(state => {
const names = [state.values['guests[]'] ?? []].flat().filter(Boolean)
show('guests', names.join(', ') || 'Nobody yet')
show('errors', state.errors['guests[]']?.[0] ?? 'None')
})
controller.onSubmit((_element, _data, formData) => {
const count = formData.getAll('guests[]').length
show('guests', `${count} invitation${count === 1 ? '' : 's'} ready`)
})
return controller
}
const element = document.querySelector('#guests')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = guests(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Collect a guest list that grows one row at a time</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="guests" class="demo-form" novalidate aria-labelledby="guests-heading">
<h1 id="guests-heading">Collect a guest list that grows one row at a time</h1>
<div class="guests" data-guests>
<div class="field" data-guest>
<label for="guest-1">Guest 1</label>
<div class="row">
<input id="guest-1" name="guests[]" autocomplete="off" />
<button type="button" data-remove>Remove</button>
</div>
</div>
</div>
<div class="actions">
<button type="button" data-add>Add guest</button>
<button type="submit">Send invitations</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Guests</dt>
<dd><output data-readout="guests">—</output></dd>
<dt>First error</dt>
<dd><output data-readout="errors">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
const guests = (element, show) => {
const list = element.querySelector('[data-guests]')
const template = list.querySelector('[data-guest]').cloneNode(true)
const controller = form(element, {
autoValidate: false,
validators: {
'guests[]': {
// `each` checks every row on its own, so only the empty row is marked.
each: { required: { value: true, message: 'Enter a name or remove the empty row.' } },
},
},
})
const renumber = () => {
list.querySelectorAll('[data-guest]').forEach((row, index) => {
const input = row.querySelector('input')
input.id = `guest-${index + 1}`
row.querySelector('label').htmlFor = input.id
row.querySelector('label').textContent = `Guest ${index + 1}`
})
}
const onClick = event => {
const target = event.target.closest('button')
if (target?.matches('[data-add]')) {
const row = template.cloneNode(true)
list.append(row)
renumber()
row.querySelector('input').focus()
} else if (target?.matches('[data-remove]') && list.children.length > 1) {
target.closest('[data-guest]').remove()
renumber()
}
}
element.addEventListener('click', onClick)
// destroy() runs registered cleanups, so the row buttons stop with the form.
controller.addCleanup(() => element.removeEventListener('click', onClick))
controller.subscribe(state => {
const names = [state.values['guests[]'] ?? []].flat().filter(Boolean)
show('guests', names.join(', ') || 'Nobody yet')
show('errors', state.errors['guests[]']?.[0] ?? 'None')
})
controller.onSubmit((_element, _data, formData) => {
const count = formData.getAll('guests[]').length
show('guests', `${count} invitation${count === 1 ? '' : 's'} ready`)
})
return controller
}
const element = document.querySelector('#guests')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = guests(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Collect a guest list that grows one row at a time</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="guests" class="demo-form" novalidate aria-labelledby="guests-heading">
<h1 id="guests-heading">Collect a guest list that grows one row at a time</h1>
<div class="guests" data-guests>
<div class="field" data-guest>
<label for="guest-1">Guest 1</label>
<div class="row">
<input id="guest-1" name="guests[]" autocomplete="off" />
<button type="button" data-remove>Remove</button>
</div>
</div>
</div>
<div class="actions">
<button type="button" data-add>Add guest</button>
<button type="submit">Send invitations</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Guests</dt>
<dd><output data-readout="guests">—</output></dd>
<dt>First error</dt>
<dd><output data-readout="errors">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
const guests = (element, show) => {
const list = element.querySelector('[data-guests]')
const template = list.querySelector('[data-guest]').cloneNode(true)
const controller = form(element, {
autoValidate: false,
validators: {
'guests[]': {
// `each` checks every row on its own, so only the empty row is marked.
each: { required: { value: true, message: 'Enter a name or remove the empty row.' } },
},
},
})
const renumber = () => {
list.querySelectorAll('[data-guest]').forEach((row, index) => {
const input = row.querySelector('input')
input.id = `guest-${index + 1}`
row.querySelector('label').htmlFor = input.id
row.querySelector('label').textContent = `Guest ${index + 1}`
})
}
const onClick = event => {
const target = event.target.closest('button')
if (target?.matches('[data-add]')) {
const row = template.cloneNode(true)
list.append(row)
renumber()
row.querySelector('input').focus()
} else if (target?.matches('[data-remove]') && list.children.length > 1) {
target.closest('[data-guest]').remove()
renumber()
}
}
element.addEventListener('click', onClick)
// destroy() runs registered cleanups, so the row buttons stop with the form.
controller.addCleanup(() => element.removeEventListener('click', onClick))
controller.subscribe(state => {
const names = [state.values['guests[]'] ?? []].flat().filter(Boolean)
show('guests', names.join(', ') || 'Nobody yet')
show('errors', state.errors['guests[]']?.[0] ?? 'None')
})
controller.onSubmit((_element, _data, formData) => {
const count = formData.getAll('guests[]').length
show('guests', `${count} invitation${count === 1 ? '' : 's'} ready`)
})
return controller
}
const element = document.querySelector('#guests')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = guests(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Check one step at a time before moving on
Check one step at a time before moving on
controller.validate(['email', 'password']).isValid- Step
- Errors on this step
- Result
A two-step sign-up validates only the visible step when you press Next, then the whole form on submit. Values from the first step stay in place while you go back and forth.
validate([names]) checks a subset and returns { isValid, errors }. Rules for hidden steps still run on the final submit, so nothing is skipped.
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Check one step at a time before moving on</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="wizard" class="demo-form" novalidate aria-labelledby="wizard-heading">
<h1 id="wizard-heading">Check one step at a time before moving on</h1>
<fieldset class="step" data-step="0">
<legend>1 · Account</legend>
<div class="field">
<label for="wizard-email">Email</label>
<input
type="email"
id="wizard-email"
name="email"
autocomplete="email"
aria-describedby="wizard-email-error"
/>
<p class="error" id="wizard-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="wizard-password">Password</label>
<input
type="password"
id="wizard-password"
name="password"
autocomplete="new-password"
aria-describedby="wizard-password-help wizard-password-error"
/>
<p class="help" id="wizard-password-help">At least 8 characters.</p>
<p
class="error"
id="wizard-password-error"
data-error-for="password"
aria-live="polite"
></p>
</div>
</fieldset>
<fieldset class="step" data-step="1" hidden>
<legend>2 · Profile</legend>
<div class="field">
<label for="wizard-company">Company</label>
<input
type="text"
id="wizard-company"
name="company"
autocomplete="organization"
aria-describedby="wizard-company-error"
/>
<p
class="error"
id="wizard-company-error"
data-error-for="company"
aria-live="polite"
></p>
</div>
<div class="field">
<label for="wizard-role">Role</label>
<select id="wizard-role" name="role" aria-describedby="wizard-role-error">
<option value="">Choose a role</option>
<option value="engineer">Engineer</option>
<option value="designer">Designer</option>
<option value="manager">Manager</option>
</select>
<p class="error" id="wizard-role-error" data-error-for="role" aria-live="polite"></p>
</div>
</fieldset>
<div class="actions">
<button type="button" data-back>Back</button>
<button type="button" data-next>Next</button>
<button type="submit">Create workspace</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Step</dt>
<dd><output data-readout="step">—</output></dd>
<dt>Errors on this step</dt>
<dd><output data-readout="errors">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const wizard = (element, show) => {
const steps = [...element.querySelectorAll('[data-step]')]
const back = element.querySelector('[data-back]')
const next = element.querySelector('[data-next]')
const submit = element.querySelector('button[type="submit"]')
const stepFields = [
['email', 'password'],
['company', 'role'],
]
let current = 0
const controller = form(element, {
autoValidate: false,
validators: {
email: {
required: { value: true, message: 'Enter your email.' },
pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Use a valid email address.' },
},
password: {
required: { value: true, message: 'Choose a password.' },
minLength: { value: 8, message: 'Use at least 8 characters.' },
},
company: { required: { value: true, message: 'Name your company.' } },
role: { required: { value: true, message: 'Choose a role.' } },
},
})
const go = index => {
current = index
steps.forEach((step, position) => {
step.hidden = position !== index
})
back.hidden = index === 0
next.hidden = index === steps.length - 1
submit.hidden = index !== steps.length - 1
show('step', `${index + 1} of ${steps.length}`)
}
const onClick = event => {
if (event.target.closest('[data-next]')) {
// Check only the fields of the visible step.
// validate() returns the result without notifying subscribers.
const { isValid, errors } = controller.validate(stepFields[current])
renderErrors(element, errors)
const count = Object.keys(errors).length
show('errors', count === 0 ? 'None' : `${count} field${count === 1 ? '' : 's'} to fix`)
if (isValid) {
go(current + 1)
steps[current].querySelector('input, select')?.focus()
}
} else if (event.target.closest('[data-back]')) {
go(current - 1)
}
}
element.addEventListener('click', onClick)
controller.addCleanup(() => element.removeEventListener('click', onClick))
controller.subscribe(state => renderErrors(element, state.errors))
controller.onSubmit((_element, data) => {
show('result', `Workspace for ${data.company} (${data.role}) is ready`)
})
go(0)
return controller
}
const element = document.querySelector('#wizard')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = wizard(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Check one step at a time before moving on</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="wizard" class="demo-form" novalidate aria-labelledby="wizard-heading">
<h1 id="wizard-heading">Check one step at a time before moving on</h1>
<fieldset class="step" data-step="0">
<legend>1 · Account</legend>
<div class="field">
<label for="wizard-email">Email</label>
<input
type="email"
id="wizard-email"
name="email"
autocomplete="email"
aria-describedby="wizard-email-error"
/>
<p class="error" id="wizard-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="wizard-password">Password</label>
<input
type="password"
id="wizard-password"
name="password"
autocomplete="new-password"
aria-describedby="wizard-password-help wizard-password-error"
/>
<p class="help" id="wizard-password-help">At least 8 characters.</p>
<p
class="error"
id="wizard-password-error"
data-error-for="password"
aria-live="polite"
></p>
</div>
</fieldset>
<fieldset class="step" data-step="1" hidden>
<legend>2 · Profile</legend>
<div class="field">
<label for="wizard-company">Company</label>
<input
type="text"
id="wizard-company"
name="company"
autocomplete="organization"
aria-describedby="wizard-company-error"
/>
<p
class="error"
id="wizard-company-error"
data-error-for="company"
aria-live="polite"
></p>
</div>
<div class="field">
<label for="wizard-role">Role</label>
<select id="wizard-role" name="role" aria-describedby="wizard-role-error">
<option value="">Choose a role</option>
<option value="engineer">Engineer</option>
<option value="designer">Designer</option>
<option value="manager">Manager</option>
</select>
<p class="error" id="wizard-role-error" data-error-for="role" aria-live="polite"></p>
</div>
</fieldset>
<div class="actions">
<button type="button" data-back>Back</button>
<button type="button" data-next>Next</button>
<button type="submit">Create workspace</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Step</dt>
<dd><output data-readout="step">—</output></dd>
<dt>Errors on this step</dt>
<dd><output data-readout="errors">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const wizard = (element, show) => {
const steps = [...element.querySelectorAll('[data-step]')]
const back = element.querySelector('[data-back]')
const next = element.querySelector('[data-next]')
const submit = element.querySelector('button[type="submit"]')
const stepFields = [
['email', 'password'],
['company', 'role'],
]
let current = 0
const controller = form(element, {
autoValidate: false,
validators: {
email: {
required: { value: true, message: 'Enter your email.' },
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: 'Use a valid email address.',
},
},
password: {
required: { value: true, message: 'Choose a password.' },
minLength: { value: 8, message: 'Use at least 8 characters.' },
},
company: { required: { value: true, message: 'Name your company.' } },
role: { required: { value: true, message: 'Choose a role.' } },
},
})
const go = index => {
current = index
steps.forEach((step, position) => {
step.hidden = position !== index
})
back.hidden = index === 0
next.hidden = index === steps.length - 1
submit.hidden = index !== steps.length - 1
show('step', `${index + 1} of ${steps.length}`)
}
const onClick = event => {
if (event.target.closest('[data-next]')) {
// Check only the fields of the visible step.
// validate() returns the result without notifying subscribers.
const { isValid, errors } = controller.validate(stepFields[current])
renderErrors(element, errors)
const count = Object.keys(errors).length
show('errors', count === 0 ? 'None' : `${count} field${count === 1 ? '' : 's'} to fix`)
if (isValid) {
go(current + 1)
steps[current].querySelector('input, select')?.focus()
}
} else if (event.target.closest('[data-back]')) {
go(current - 1)
}
}
element.addEventListener('click', onClick)
controller.addCleanup(() => element.removeEventListener('click', onClick))
controller.subscribe(state => renderErrors(element, state.errors))
controller.onSubmit((_element, data) => {
show('result', `Workspace for ${data.company} (${data.role}) is ready`)
})
go(0)
return controller
}
const element = document.querySelector('#wizard')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = wizard(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Check one step at a time before moving on</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="wizard" class="demo-form" novalidate aria-labelledby="wizard-heading">
<h1 id="wizard-heading">Check one step at a time before moving on</h1>
<fieldset class="step" data-step="0">
<legend>1 · Account</legend>
<div class="field">
<label for="wizard-email">Email</label>
<input
type="email"
id="wizard-email"
name="email"
autocomplete="email"
aria-describedby="wizard-email-error"
/>
<p class="error" id="wizard-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="wizard-password">Password</label>
<input
type="password"
id="wizard-password"
name="password"
autocomplete="new-password"
aria-describedby="wizard-password-help wizard-password-error"
/>
<p class="help" id="wizard-password-help">At least 8 characters.</p>
<p
class="error"
id="wizard-password-error"
data-error-for="password"
aria-live="polite"
></p>
</div>
</fieldset>
<fieldset class="step" data-step="1" hidden>
<legend>2 · Profile</legend>
<div class="field">
<label for="wizard-company">Company</label>
<input
type="text"
id="wizard-company"
name="company"
autocomplete="organization"
aria-describedby="wizard-company-error"
/>
<p
class="error"
id="wizard-company-error"
data-error-for="company"
aria-live="polite"
></p>
</div>
<div class="field">
<label for="wizard-role">Role</label>
<select id="wizard-role" name="role" aria-describedby="wizard-role-error">
<option value="">Choose a role</option>
<option value="engineer">Engineer</option>
<option value="designer">Designer</option>
<option value="manager">Manager</option>
</select>
<p class="error" id="wizard-role-error" data-error-for="role" aria-live="polite"></p>
</div>
</fieldset>
<div class="actions">
<button type="button" data-back>Back</button>
<button type="button" data-next>Next</button>
<button type="submit">Create workspace</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Step</dt>
<dd><output data-readout="step">—</output></dd>
<dt>Errors on this step</dt>
<dd><output data-readout="errors">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const wizard = (element, show) => {
const steps = [...element.querySelectorAll('[data-step]')]
const back = element.querySelector('[data-back]')
const next = element.querySelector('[data-next]')
const submit = element.querySelector('button[type="submit"]')
const stepFields = [
['email', 'password'],
['company', 'role'],
]
let current = 0
const controller = form(element, {
autoValidate: false,
validators: {
email: {
required: { value: true, message: 'Enter your email.' },
pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Use a valid email address.' },
},
password: {
required: { value: true, message: 'Choose a password.' },
minLength: { value: 8, message: 'Use at least 8 characters.' },
},
company: { required: { value: true, message: 'Name your company.' } },
role: { required: { value: true, message: 'Choose a role.' } },
},
})
const go = index => {
current = index
steps.forEach((step, position) => {
step.hidden = position !== index
})
back.hidden = index === 0
next.hidden = index === steps.length - 1
submit.hidden = index !== steps.length - 1
show('step', `${index + 1} of ${steps.length}`)
}
const onClick = event => {
if (event.target.closest('[data-next]')) {
// Check only the fields of the visible step.
// validate() returns the result without notifying subscribers.
const { isValid, errors } = controller.validate(stepFields[current])
renderErrors(element, errors)
const count = Object.keys(errors).length
show('errors', count === 0 ? 'None' : `${count} field${count === 1 ? '' : 's'} to fix`)
if (isValid) {
go(current + 1)
steps[current].querySelector('input, select')?.focus()
}
} else if (event.target.closest('[data-back]')) {
go(current - 1)
}
}
element.addEventListener('click', onClick)
controller.addCleanup(() => element.removeEventListener('click', onClick))
controller.subscribe(state => renderErrors(element, state.errors))
controller.onSubmit((_element, data) => {
show('result', `Workspace for ${data.company} (${data.role}) is ready`)
})
go(0)
return controller
}
const element = document.querySelector('#wizard')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = wizard(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Check one step at a time before moving on</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="wizard" class="demo-form" novalidate aria-labelledby="wizard-heading">
<h1 id="wizard-heading">Check one step at a time before moving on</h1>
<fieldset class="step" data-step="0">
<legend>1 · Account</legend>
<div class="field">
<label for="wizard-email">Email</label>
<input
type="email"
id="wizard-email"
name="email"
autocomplete="email"
aria-describedby="wizard-email-error"
/>
<p class="error" id="wizard-email-error" data-error-for="email" aria-live="polite"></p>
</div>
<div class="field">
<label for="wizard-password">Password</label>
<input
type="password"
id="wizard-password"
name="password"
autocomplete="new-password"
aria-describedby="wizard-password-help wizard-password-error"
/>
<p class="help" id="wizard-password-help">At least 8 characters.</p>
<p
class="error"
id="wizard-password-error"
data-error-for="password"
aria-live="polite"
></p>
</div>
</fieldset>
<fieldset class="step" data-step="1" hidden>
<legend>2 · Profile</legend>
<div class="field">
<label for="wizard-company">Company</label>
<input
type="text"
id="wizard-company"
name="company"
autocomplete="organization"
aria-describedby="wizard-company-error"
/>
<p
class="error"
id="wizard-company-error"
data-error-for="company"
aria-live="polite"
></p>
</div>
<div class="field">
<label for="wizard-role">Role</label>
<select id="wizard-role" name="role" aria-describedby="wizard-role-error">
<option value="">Choose a role</option>
<option value="engineer">Engineer</option>
<option value="designer">Designer</option>
<option value="manager">Manager</option>
</select>
<p class="error" id="wizard-role-error" data-error-for="role" aria-live="polite"></p>
</div>
</fieldset>
<div class="actions">
<button type="button" data-back>Back</button>
<button type="button" data-next>Next</button>
<button type="submit">Create workspace</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Step</dt>
<dd><output data-readout="step">—</output></dd>
<dt>Errors on this step</dt>
<dd><output data-readout="errors">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const wizard = (element, show) => {
const steps = [...element.querySelectorAll('[data-step]')]
const back = element.querySelector('[data-back]')
const next = element.querySelector('[data-next]')
const submit = element.querySelector('button[type="submit"]')
const stepFields = [
['email', 'password'],
['company', 'role'],
]
let current = 0
const controller = form(element, {
autoValidate: false,
validators: {
email: {
required: { value: true, message: 'Enter your email.' },
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: 'Use a valid email address.',
},
},
password: {
required: { value: true, message: 'Choose a password.' },
minLength: { value: 8, message: 'Use at least 8 characters.' },
},
company: { required: { value: true, message: 'Name your company.' } },
role: { required: { value: true, message: 'Choose a role.' } },
},
})
const go = index => {
current = index
steps.forEach((step, position) => {
step.hidden = position !== index
})
back.hidden = index === 0
next.hidden = index === steps.length - 1
submit.hidden = index !== steps.length - 1
show('step', `${index + 1} of ${steps.length}`)
}
const onClick = event => {
if (event.target.closest('[data-next]')) {
// Check only the fields of the visible step.
// validate() returns the result without notifying subscribers.
const { isValid, errors } = controller.validate(stepFields[current])
renderErrors(element, errors)
const count = Object.keys(errors).length
show('errors', count === 0 ? 'None' : `${count} field${count === 1 ? '' : 's'} to fix`)
if (isValid) {
go(current + 1)
steps[current].querySelector('input, select')?.focus()
}
} else if (event.target.closest('[data-back]')) {
go(current - 1)
}
}
element.addEventListener('click', onClick)
controller.addCleanup(() => element.removeEventListener('click', onClick))
controller.subscribe(state => renderErrors(element, state.errors))
controller.onSubmit((_element, data) => {
show('result', `Workspace for ${data.company} (${data.role}) is ready`)
})
go(0)
return controller
}
const element = document.querySelector('#wizard')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = wizard(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Require a date only when delivery is scheduled
Require a date only when delivery is scheduled
date: { validate: ({ value, values }) => …, dependsOn: 'method' }- Method
- Result
A custom validator reads another field. dependsOn tells the controller to re-run it when the delivery choice changes, so switching back to standard clears the error at once.
validate receives { value, values, field }. Return a message to fail, or nothing to pass. The pattern rule still checks the date format when one is entered.
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Require a date only when delivery is scheduled</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="delivery" class="demo-form" novalidate aria-labelledby="delivery-heading">
<h1 id="delivery-heading">Require a date only when delivery is scheduled</h1>
<fieldset class="field">
<legend>Delivery</legend>
<label class="check"
><input type="radio" name="method" value="standard" checked /> Standard (2–4
days)</label
>
<label class="check"
><input type="radio" name="method" value="scheduled" /> On a chosen date</label
>
</fieldset>
<div class="field">
<label for="delivery-date">Delivery date</label>
<input
type="text"
id="delivery-date"
name="date"
autocomplete="off"
inputmode="numeric"
placeholder="YYYY-MM-DD"
aria-describedby="delivery-date-error"
/>
<p class="error" id="delivery-date-error" data-error-for="date" aria-live="polite"></p>
</div>
<div class="actions">
<button type="submit">Confirm delivery</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Method</dt>
<dd><output data-readout="method">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const delivery = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
date: {
// Runs again whenever `method` changes, thanks to dependsOn.
validate: ({ value, values }) =>
values.method === 'scheduled' && !value ? 'Pick a delivery date.' : undefined,
dependsOn: 'method',
pattern: { value: /^\d{4}-\d{2}-\d{2}$/, message: 'Use the YYYY-MM-DD format.' },
},
},
})
controller.observe('method', value => show('method', String(value)))
controller.subscribe(state => renderErrors(element, state.errors))
controller.onSubmit((_element, data) => {
show('result', data.method === 'scheduled' ? `Arrives on ${data.date}` : 'Arrives in 2–4 days')
})
return controller
}
const element = document.querySelector('#delivery')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = delivery(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Require a date only when delivery is scheduled</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="delivery" class="demo-form" novalidate aria-labelledby="delivery-heading">
<h1 id="delivery-heading">Require a date only when delivery is scheduled</h1>
<fieldset class="field">
<legend>Delivery</legend>
<label class="check"
><input type="radio" name="method" value="standard" checked /> Standard (2–4
days)</label
>
<label class="check"
><input type="radio" name="method" value="scheduled" /> On a chosen date</label
>
</fieldset>
<div class="field">
<label for="delivery-date">Delivery date</label>
<input
type="text"
id="delivery-date"
name="date"
autocomplete="off"
inputmode="numeric"
placeholder="YYYY-MM-DD"
aria-describedby="delivery-date-error"
/>
<p class="error" id="delivery-date-error" data-error-for="date" aria-live="polite"></p>
</div>
<div class="actions">
<button type="submit">Confirm delivery</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Method</dt>
<dd><output data-readout="method">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const delivery = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
date: {
// Runs again whenever `method` changes, thanks to dependsOn.
validate: ({ value, values }) =>
values.method === 'scheduled' && !value ? 'Pick a delivery date.' : undefined,
dependsOn: 'method',
pattern: { value: /^\d{4}-\d{2}-\d{2}$/, message: 'Use the YYYY-MM-DD format.' },
},
},
})
controller.observe('method', value => show('method', String(value)))
controller.subscribe(state => renderErrors(element, state.errors))
controller.onSubmit((_element, data) => {
show(
'result',
data.method === 'scheduled' ? `Arrives on ${data.date}` : 'Arrives in 2–4 days'
)
})
return controller
}
const element = document.querySelector('#delivery')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = delivery(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Require a date only when delivery is scheduled</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="delivery" class="demo-form" novalidate aria-labelledby="delivery-heading">
<h1 id="delivery-heading">Require a date only when delivery is scheduled</h1>
<fieldset class="field">
<legend>Delivery</legend>
<label class="check"
><input type="radio" name="method" value="standard" checked /> Standard (2–4
days)</label
>
<label class="check"
><input type="radio" name="method" value="scheduled" /> On a chosen date</label
>
</fieldset>
<div class="field">
<label for="delivery-date">Delivery date</label>
<input
type="text"
id="delivery-date"
name="date"
autocomplete="off"
inputmode="numeric"
placeholder="YYYY-MM-DD"
aria-describedby="delivery-date-error"
/>
<p class="error" id="delivery-date-error" data-error-for="date" aria-live="polite"></p>
</div>
<div class="actions">
<button type="submit">Confirm delivery</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Method</dt>
<dd><output data-readout="method">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const delivery = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
date: {
// Runs again whenever `method` changes, thanks to dependsOn.
validate: ({ value, values }) =>
values.method === 'scheduled' && !value ? 'Pick a delivery date.' : undefined,
dependsOn: 'method',
pattern: { value: /^\d{4}-\d{2}-\d{2}$/, message: 'Use the YYYY-MM-DD format.' },
},
},
})
controller.observe('method', value => show('method', String(value)))
controller.subscribe(state => renderErrors(element, state.errors))
controller.onSubmit((_element, data) => {
show('result', data.method === 'scheduled' ? `Arrives on ${data.date}` : 'Arrives in 2–4 days')
})
return controller
}
const element = document.querySelector('#delivery')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = delivery(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Require a date only when delivery is scheduled</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="delivery" class="demo-form" novalidate aria-labelledby="delivery-heading">
<h1 id="delivery-heading">Require a date only when delivery is scheduled</h1>
<fieldset class="field">
<legend>Delivery</legend>
<label class="check"
><input type="radio" name="method" value="standard" checked /> Standard (2–4
days)</label
>
<label class="check"
><input type="radio" name="method" value="scheduled" /> On a chosen date</label
>
</fieldset>
<div class="field">
<label for="delivery-date">Delivery date</label>
<input
type="text"
id="delivery-date"
name="date"
autocomplete="off"
inputmode="numeric"
placeholder="YYYY-MM-DD"
aria-describedby="delivery-date-error"
/>
<p class="error" id="delivery-date-error" data-error-for="date" aria-live="polite"></p>
</div>
<div class="actions">
<button type="submit">Confirm delivery</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Method</dt>
<dd><output data-readout="method">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const delivery = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
date: {
// Runs again whenever `method` changes, thanks to dependsOn.
validate: ({ value, values }) =>
values.method === 'scheduled' && !value ? 'Pick a delivery date.' : undefined,
dependsOn: 'method',
pattern: { value: /^\d{4}-\d{2}-\d{2}$/, message: 'Use the YYYY-MM-DD format.' },
},
},
})
controller.observe('method', value => show('method', String(value)))
controller.subscribe(state => renderErrors(element, state.errors))
controller.onSubmit((_element, data) => {
show(
'result',
data.method === 'scheduled' ? `Arrives on ${data.date}` : 'Arrives in 2–4 days'
)
})
return controller
}
const element = document.querySelector('#delivery')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = delivery(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Keep a quantity in range and show the total as you type
Keep a quantity in range and show the total as you type
quantity: { required: true, numeric: true, min: 1, max: 10 }- Total
- Status
numeric, min and max reject text, decimals outside the range and empty values on submit, while observe() recalculates the total on every keystroke.
Numeric rules accept strict decimal strings such as 3 or 2.5 and skip empty values; add required for a mandatory field. The price lives in the script, not in a hidden input.
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Keep a quantity in range and show the total as you type</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form
id="order"
class="demo-form"
data-errors="filled"
novalidate
aria-labelledby="order-heading"
>
<h1 id="order-heading">Keep a quantity in range and show the total as you type</h1>
<div class="field">
<label for="order-quantity">Seats</label>
<input
type="text"
id="order-quantity"
name="quantity"
autocomplete="off"
inputmode="numeric"
aria-describedby="order-quantity-help order-quantity-error"
value="2"
/>
<p class="help" id="order-quantity-help">$24 per seat, up to 10 seats.</p>
<p
class="error"
id="order-quantity-error"
data-error-for="quantity"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Buy seats</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Total</dt>
<dd><output data-readout="total">—</output></dd>
<dt>Status</dt>
<dd><output data-readout="status">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const seatPrice = 24
const order = (element, show) => {
const controller = form(element, {
validators: {
quantity: {
required: { value: true, message: 'Enter how many seats you need.' },
numeric: { value: true, message: 'Use digits, for example 3.' },
min: { value: 1, message: 'Buy at least 1 seat.' },
max: { value: 10, message: 'Contact us for more than 10 seats.' },
},
},
})
controller.observe('quantity', value => {
const seats = Number(value)
show('total', Number.isFinite(seats) && seats > 0 ? `$${(seats * seatPrice).toFixed(2)}` : '—')
})
controller.subscribe(state => {
renderErrors(element, state.errors)
show('status', state.errors.quantity?.[0] ?? 'Ready to buy')
})
controller.onSubmit((_element, data) => {
show('status', `Reserved ${data.quantity} seats`)
})
return controller
}
const element = document.querySelector('#order')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = order(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Keep a quantity in range and show the total as you type</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form
id="order"
class="demo-form"
data-errors="filled"
novalidate
aria-labelledby="order-heading"
>
<h1 id="order-heading">Keep a quantity in range and show the total as you type</h1>
<div class="field">
<label for="order-quantity">Seats</label>
<input
type="text"
id="order-quantity"
name="quantity"
autocomplete="off"
inputmode="numeric"
aria-describedby="order-quantity-help order-quantity-error"
value="2"
/>
<p class="help" id="order-quantity-help">$24 per seat, up to 10 seats.</p>
<p
class="error"
id="order-quantity-error"
data-error-for="quantity"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Buy seats</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Total</dt>
<dd><output data-readout="total">—</output></dd>
<dt>Status</dt>
<dd><output data-readout="status">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const seatPrice = 24
const order = (element, show) => {
const controller = form(element, {
validators: {
quantity: {
required: { value: true, message: 'Enter how many seats you need.' },
numeric: { value: true, message: 'Use digits, for example 3.' },
min: { value: 1, message: 'Buy at least 1 seat.' },
max: { value: 10, message: 'Contact us for more than 10 seats.' },
},
},
})
controller.observe('quantity', value => {
const seats = Number(value)
show(
'total',
Number.isFinite(seats) && seats > 0 ? `$${(seats * seatPrice).toFixed(2)}` : '—'
)
})
controller.subscribe(state => {
renderErrors(element, state.errors)
show('status', state.errors.quantity?.[0] ?? 'Ready to buy')
})
controller.onSubmit((_element, data) => {
show('status', `Reserved ${data.quantity} seats`)
})
return controller
}
const element = document.querySelector('#order')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = order(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Keep a quantity in range and show the total as you type</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form
id="order"
class="demo-form"
data-errors="filled"
novalidate
aria-labelledby="order-heading"
>
<h1 id="order-heading">Keep a quantity in range and show the total as you type</h1>
<div class="field">
<label for="order-quantity">Seats</label>
<input
type="text"
id="order-quantity"
name="quantity"
autocomplete="off"
inputmode="numeric"
aria-describedby="order-quantity-help order-quantity-error"
value="2"
/>
<p class="help" id="order-quantity-help">$24 per seat, up to 10 seats.</p>
<p
class="error"
id="order-quantity-error"
data-error-for="quantity"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Buy seats</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Total</dt>
<dd><output data-readout="total">—</output></dd>
<dt>Status</dt>
<dd><output data-readout="status">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const seatPrice = 24
const order = (element, show) => {
const controller = form(element, {
validators: {
quantity: {
required: { value: true, message: 'Enter how many seats you need.' },
numeric: { value: true, message: 'Use digits, for example 3.' },
min: { value: 1, message: 'Buy at least 1 seat.' },
max: { value: 10, message: 'Contact us for more than 10 seats.' },
},
},
})
controller.observe('quantity', value => {
const seats = Number(value)
show('total', Number.isFinite(seats) && seats > 0 ? `$${(seats * seatPrice).toFixed(2)}` : '—')
})
controller.subscribe(state => {
renderErrors(element, state.errors)
show('status', state.errors.quantity?.[0] ?? 'Ready to buy')
})
controller.onSubmit((_element, data) => {
show('status', `Reserved ${data.quantity} seats`)
})
return controller
}
const element = document.querySelector('#order')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = order(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Keep a quantity in range and show the total as you type</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form
id="order"
class="demo-form"
data-errors="filled"
novalidate
aria-labelledby="order-heading"
>
<h1 id="order-heading">Keep a quantity in range and show the total as you type</h1>
<div class="field">
<label for="order-quantity">Seats</label>
<input
type="text"
id="order-quantity"
name="quantity"
autocomplete="off"
inputmode="numeric"
aria-describedby="order-quantity-help order-quantity-error"
value="2"
/>
<p class="help" id="order-quantity-help">$24 per seat, up to 10 seats.</p>
<p
class="error"
id="order-quantity-error"
data-error-for="quantity"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Buy seats</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Total</dt>
<dd><output data-readout="total">—</output></dd>
<dt>Status</dt>
<dd><output data-readout="status">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const seatPrice = 24
const order = (element, show) => {
const controller = form(element, {
validators: {
quantity: {
required: { value: true, message: 'Enter how many seats you need.' },
numeric: { value: true, message: 'Use digits, for example 3.' },
min: { value: 1, message: 'Buy at least 1 seat.' },
max: { value: 10, message: 'Contact us for more than 10 seats.' },
},
},
})
controller.observe('quantity', value => {
const seats = Number(value)
show(
'total',
Number.isFinite(seats) && seats > 0 ? `$${(seats * seatPrice).toFixed(2)}` : '—'
)
})
controller.subscribe(state => {
renderErrors(element, state.errors)
show('status', state.errors.quantity?.[0] ?? 'Ready to buy')
})
controller.onSubmit((_element, data) => {
show('status', `Reserved ${data.quantity} seats`)
})
return controller
}
const element = document.querySelector('#order')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = order(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Read radios, checkbox groups, multiple selects and a consent box
Read radios, checkbox groups, multiple selects and a consent box
controller.getValue('days') // ['mon', 'thu']- getState().values
- Result
Every native control reports a predictable value: a radio group gives one string, a checkbox group and a multiple select give lists, and a single checkbox gives its value or an empty string.
A bare checkbox group returns a string for one checked box and an array for several; name it topics[] to always get an array. minLength on a group counts selected items.
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Read radios, checkbox groups, multiple selects and a consent box</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="preferences" class="demo-form" novalidate aria-labelledby="preferences-heading">
<h1 id="preferences-heading">
Read radios, checkbox groups, multiple selects and a consent box
</h1>
<fieldset class="field">
<legend>Contact me by</legend>
<label class="check"
><input type="radio" name="channel" value="email" checked /> Email</label
>
<label class="check"><input type="radio" name="channel" value="sms" /> SMS</label>
</fieldset>
<fieldset class="field" aria-describedby="preferences-topics-error">
<legend>Topics</legend>
<label class="check"
><input type="checkbox" name="topics[]" value="releases" /> Releases</label
>
<label class="check"
><input type="checkbox" name="topics[]" value="events" /> Events</label
>
<label class="check"><input type="checkbox" name="topics[]" value="tips" /> Tips</label>
<p
class="error"
id="preferences-topics-error"
data-error-for="topics[]"
aria-live="polite"
></p>
</fieldset>
<div class="field">
<label for="preferences-days">Best days</label>
<select id="preferences-days" name="days" multiple size="5">
<option value="mon">Monday</option>
<option value="tue">Tuesday</option>
<option value="wed">Wednesday</option>
<option value="thu">Thursday</option>
<option value="fri">Friday</option>
</select>
</div>
<div class="field">
<label class="check"
><input
type="checkbox"
id="preferences-consent"
name="consent"
value="yes"
aria-describedby="preferences-consent-error"
/>
I agree to receive these messages</label
>
<p
class="error"
id="preferences-consent-error"
data-error-for="consent"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Save preferences</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>getState().values</dt>
<dd><output data-readout="values">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const preferences = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
'topics[]': { minLength: { value: 1, message: 'Pick at least one topic.' } },
consent: { required: { value: true, message: 'Tick the box to subscribe.' } },
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
const { channel, days, consent } = state.values
show('values', JSON.stringify({ channel, 'topics[]': state.values['topics[]'], days, consent }))
})
controller.onSubmit((_element, data) => {
show('result', `Saved ${[data['topics[]']].flat().length} topic(s) by ${data.channel}`)
})
return controller
}
const element = document.querySelector('#preferences')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = preferences(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Read radios, checkbox groups, multiple selects and a consent box</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="preferences" class="demo-form" novalidate aria-labelledby="preferences-heading">
<h1 id="preferences-heading">
Read radios, checkbox groups, multiple selects and a consent box
</h1>
<fieldset class="field">
<legend>Contact me by</legend>
<label class="check"
><input type="radio" name="channel" value="email" checked /> Email</label
>
<label class="check"><input type="radio" name="channel" value="sms" /> SMS</label>
</fieldset>
<fieldset class="field" aria-describedby="preferences-topics-error">
<legend>Topics</legend>
<label class="check"
><input type="checkbox" name="topics[]" value="releases" /> Releases</label
>
<label class="check"
><input type="checkbox" name="topics[]" value="events" /> Events</label
>
<label class="check"><input type="checkbox" name="topics[]" value="tips" /> Tips</label>
<p
class="error"
id="preferences-topics-error"
data-error-for="topics[]"
aria-live="polite"
></p>
</fieldset>
<div class="field">
<label for="preferences-days">Best days</label>
<select id="preferences-days" name="days" multiple size="5">
<option value="mon">Monday</option>
<option value="tue">Tuesday</option>
<option value="wed">Wednesday</option>
<option value="thu">Thursday</option>
<option value="fri">Friday</option>
</select>
</div>
<div class="field">
<label class="check"
><input
type="checkbox"
id="preferences-consent"
name="consent"
value="yes"
aria-describedby="preferences-consent-error"
/>
I agree to receive these messages</label
>
<p
class="error"
id="preferences-consent-error"
data-error-for="consent"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Save preferences</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>getState().values</dt>
<dd><output data-readout="values">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const preferences = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
'topics[]': { minLength: { value: 1, message: 'Pick at least one topic.' } },
consent: { required: { value: true, message: 'Tick the box to subscribe.' } },
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
const { channel, days, consent } = state.values
show(
'values',
JSON.stringify({ channel, 'topics[]': state.values['topics[]'], days, consent })
)
})
controller.onSubmit((_element, data) => {
show('result', `Saved ${[data['topics[]']].flat().length} topic(s) by ${data.channel}`)
})
return controller
}
const element = document.querySelector('#preferences')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = preferences(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Read radios, checkbox groups, multiple selects and a consent box</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="preferences" class="demo-form" novalidate aria-labelledby="preferences-heading">
<h1 id="preferences-heading">
Read radios, checkbox groups, multiple selects and a consent box
</h1>
<fieldset class="field">
<legend>Contact me by</legend>
<label class="check"
><input type="radio" name="channel" value="email" checked /> Email</label
>
<label class="check"><input type="radio" name="channel" value="sms" /> SMS</label>
</fieldset>
<fieldset class="field" aria-describedby="preferences-topics-error">
<legend>Topics</legend>
<label class="check"
><input type="checkbox" name="topics[]" value="releases" /> Releases</label
>
<label class="check"
><input type="checkbox" name="topics[]" value="events" /> Events</label
>
<label class="check"><input type="checkbox" name="topics[]" value="tips" /> Tips</label>
<p
class="error"
id="preferences-topics-error"
data-error-for="topics[]"
aria-live="polite"
></p>
</fieldset>
<div class="field">
<label for="preferences-days">Best days</label>
<select id="preferences-days" name="days" multiple size="5">
<option value="mon">Monday</option>
<option value="tue">Tuesday</option>
<option value="wed">Wednesday</option>
<option value="thu">Thursday</option>
<option value="fri">Friday</option>
</select>
</div>
<div class="field">
<label class="check"
><input
type="checkbox"
id="preferences-consent"
name="consent"
value="yes"
aria-describedby="preferences-consent-error"
/>
I agree to receive these messages</label
>
<p
class="error"
id="preferences-consent-error"
data-error-for="consent"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Save preferences</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>getState().values</dt>
<dd><output data-readout="values">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const preferences = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
'topics[]': { minLength: { value: 1, message: 'Pick at least one topic.' } },
consent: { required: { value: true, message: 'Tick the box to subscribe.' } },
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
const { channel, days, consent } = state.values
show('values', JSON.stringify({ channel, 'topics[]': state.values['topics[]'], days, consent }))
})
controller.onSubmit((_element, data) => {
show('result', `Saved ${[data['topics[]']].flat().length} topic(s) by ${data.channel}`)
})
return controller
}
const element = document.querySelector('#preferences')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = preferences(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Read radios, checkbox groups, multiple selects and a consent box</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="preferences" class="demo-form" novalidate aria-labelledby="preferences-heading">
<h1 id="preferences-heading">
Read radios, checkbox groups, multiple selects and a consent box
</h1>
<fieldset class="field">
<legend>Contact me by</legend>
<label class="check"
><input type="radio" name="channel" value="email" checked /> Email</label
>
<label class="check"><input type="radio" name="channel" value="sms" /> SMS</label>
</fieldset>
<fieldset class="field" aria-describedby="preferences-topics-error">
<legend>Topics</legend>
<label class="check"
><input type="checkbox" name="topics[]" value="releases" /> Releases</label
>
<label class="check"
><input type="checkbox" name="topics[]" value="events" /> Events</label
>
<label class="check"><input type="checkbox" name="topics[]" value="tips" /> Tips</label>
<p
class="error"
id="preferences-topics-error"
data-error-for="topics[]"
aria-live="polite"
></p>
</fieldset>
<div class="field">
<label for="preferences-days">Best days</label>
<select id="preferences-days" name="days" multiple size="5">
<option value="mon">Monday</option>
<option value="tue">Tuesday</option>
<option value="wed">Wednesday</option>
<option value="thu">Thursday</option>
<option value="fri">Friday</option>
</select>
</div>
<div class="field">
<label class="check"
><input
type="checkbox"
id="preferences-consent"
name="consent"
value="yes"
aria-describedby="preferences-consent-error"
/>
I agree to receive these messages</label
>
<p
class="error"
id="preferences-consent-error"
data-error-for="consent"
aria-live="polite"
></p>
</div>
<div class="actions">
<button type="submit">Save preferences</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>getState().values</dt>
<dd><output data-readout="values">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
/** Write the first message of every field into its [data-error-for] slot. */
const renderErrors = (element, errors) => {
for (const slot of element.querySelectorAll('[data-error-for]')) {
slot.textContent = errors[slot.dataset.errorFor]?.[0] ?? ''
}
}
const preferences = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
'topics[]': { minLength: { value: 1, message: 'Pick at least one topic.' } },
consent: { required: { value: true, message: 'Tick the box to subscribe.' } },
},
})
controller.subscribe(state => {
renderErrors(element, state.errors)
const { channel, days, consent } = state.values
show(
'values',
JSON.stringify({ channel, 'topics[]': state.values['topics[]'], days, consent })
)
})
controller.onSubmit((_element, data) => {
show('result', `Saved ${[data['topics[]']].flat().length} topic(s) by ${data.channel}`)
})
return controller
}
const element = document.querySelector('#preferences')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = preferences(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Float labels with your own attribute names
Float labels with your own attribute names
form(element, { attributes: { filled: 'data-filled', error: 'data-invalid' } })- Email attributes
- Result
The attributes option renames css-filled and css-error, so the form follows your design system. Labels rise when a field is filled, and invalid fields turn red only after you type.
The controller only toggles attributes; all styling is CSS. Selectors such as .field:has([data-filled]) style the wrapper without extra JavaScript.
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Float labels with your own attribute names</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form
id="floating"
class="demo-form"
data-variant="floating"
novalidate
aria-labelledby="floating-heading"
>
<h1 id="floating-heading">Float labels with your own attribute names</h1>
<div class="field">
<label for="floating-name">Name</label>
<input type="text" id="floating-name" name="name" autocomplete="name" />
</div>
<div class="field">
<label for="floating-email">Email</label>
<input type="email" id="floating-email" name="email" autocomplete="email" />
</div>
<div class="actions">
<button type="submit">Join the list</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Email attributes</dt>
<dd><output data-readout="attributes">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
const floating = (element, show) => {
const email = element.querySelector('input[type="email"]')
const controller = form(element, {
// Your own attribute names instead of css-filled and css-error.
attributes: { filled: 'data-filled', error: 'data-invalid' },
validators: {
name: { required: true },
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
},
})
controller.subscribe(() => {
const names = ['data-filled', 'data-invalid', 'aria-invalid'].filter(name =>
email.hasAttribute(name)
)
show('attributes', names.join(' ') || 'none')
})
controller.onSubmit((_element, data) => {
show('result', `${data.name} joined the list`)
})
return controller
}
const element = document.querySelector('#floating')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = floating(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Float labels with your own attribute names</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form
id="floating"
class="demo-form"
data-variant="floating"
novalidate
aria-labelledby="floating-heading"
>
<h1 id="floating-heading">Float labels with your own attribute names</h1>
<div class="field">
<label for="floating-name">Name</label>
<input type="text" id="floating-name" name="name" autocomplete="name" />
</div>
<div class="field">
<label for="floating-email">Email</label>
<input type="email" id="floating-email" name="email" autocomplete="email" />
</div>
<div class="actions">
<button type="submit">Join the list</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Email attributes</dt>
<dd><output data-readout="attributes">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
const floating = (element, show) => {
const email = element.querySelector('input[type="email"]')
const controller = form(element, {
// Your own attribute names instead of css-filled and css-error.
attributes: { filled: 'data-filled', error: 'data-invalid' },
validators: {
name: { required: true },
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
},
})
controller.subscribe(() => {
const names = ['data-filled', 'data-invalid', 'aria-invalid'].filter(name =>
email.hasAttribute(name)
)
show('attributes', names.join(' ') || 'none')
})
controller.onSubmit((_element, data) => {
show('result', `${data.name} joined the list`)
})
return controller
}
const element = document.querySelector('#floating')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = floating(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Float labels with your own attribute names</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form
id="floating"
class="demo-form"
data-variant="floating"
novalidate
aria-labelledby="floating-heading"
>
<h1 id="floating-heading">Float labels with your own attribute names</h1>
<div class="field">
<label for="floating-name">Name</label>
<input type="text" id="floating-name" name="name" autocomplete="name" />
</div>
<div class="field">
<label for="floating-email">Email</label>
<input type="email" id="floating-email" name="email" autocomplete="email" />
</div>
<div class="actions">
<button type="submit">Join the list</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Email attributes</dt>
<dd><output data-readout="attributes">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
const floating = (element, show) => {
const email = element.querySelector('input[type="email"]')
const controller = form(element, {
// Your own attribute names instead of css-filled and css-error.
attributes: { filled: 'data-filled', error: 'data-invalid' },
validators: {
name: { required: true },
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
},
})
controller.subscribe(() => {
const names = ['data-filled', 'data-invalid', 'aria-invalid'].filter(name =>
email.hasAttribute(name)
)
show('attributes', names.join(' ') || 'none')
})
controller.onSubmit((_element, data) => {
show('result', `${data.name} joined the list`)
})
return controller
}
const element = document.querySelector('#floating')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = floating(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Float labels with your own attribute names</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form
id="floating"
class="demo-form"
data-variant="floating"
novalidate
aria-labelledby="floating-heading"
>
<h1 id="floating-heading">Float labels with your own attribute names</h1>
<div class="field">
<label for="floating-name">Name</label>
<input type="text" id="floating-name" name="name" autocomplete="name" />
</div>
<div class="field">
<label for="floating-email">Email</label>
<input type="email" id="floating-email" name="email" autocomplete="email" />
</div>
<div class="actions">
<button type="submit">Join the list</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Email attributes</dt>
<dd><output data-readout="attributes">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
const floating = (element, show) => {
const email = element.querySelector('input[type="email"]')
const controller = form(element, {
// Your own attribute names instead of css-filled and css-error.
attributes: { filled: 'data-filled', error: 'data-invalid' },
validators: {
name: { required: true },
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
},
})
controller.subscribe(() => {
const names = ['data-filled', 'data-invalid', 'aria-invalid'].filter(name =>
email.hasAttribute(name)
)
show('attributes', names.join(' ') || 'none')
})
controller.onSubmit((_element, data) => {
show('result', `${data.name} joined the list`)
})
return controller
}
const element = document.querySelector('#floating')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = floating(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
List every problem at the top after a failed submit
List every problem at the top after a failed submit
controller.append({ tag: 'div', class: 'error-summary', content, atStart: true })- Problems
- Result
A subscriber notices each new submit attempt and inserts one summary with append(): every message links to its field, and the list disappears once the form is valid.
append() replaces an earlier node with the same class, so the summary never duplicates. Rendering into the form no longer re-triggers validation (fixed in 2.8.0).
Explore the code
HTML / CDN
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>List every problem at the top after a failed submit</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="summary" class="demo-form" novalidate aria-labelledby="summary-heading">
<h1 id="summary-heading">List every problem at the top after a failed submit</h1>
<div class="field">
<label for="summary-title">Event title</label>
<input type="text" id="summary-title" name="title" autocomplete="off" />
</div>
<div class="field">
<label for="summary-venue">Venue</label>
<input type="text" id="summary-venue" name="venue" autocomplete="off" />
</div>
<div class="field">
<label for="summary-capacity">Capacity</label>
<input
type="text"
id="summary-capacity"
name="capacity"
autocomplete="off"
inputmode="numeric"
/>
</div>
<div class="actions">
<button type="submit">Publish event</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Problems</dt>
<dd><output data-readout="problems">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script src="./main.js" defer></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
const { form } = window.Forms
const summary = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
title: { required: { value: true, message: 'Add an event title.' } },
venue: { required: { value: true, message: 'Say where it happens.' } },
capacity: {
required: { value: true, message: 'Set a capacity.' },
numeric: { value: true, message: 'Capacity must be a number.' },
},
},
})
let attempts = 0
controller.subscribe(state => {
const entries = Object.entries(state.errors)
show('problems', String(entries.length))
if (entries.length === 0) element.querySelector('.error-summary')?.remove()
// Rebuild the summary once per submit attempt, not on every keystroke.
if (state.submitCount === attempts || entries.length === 0) return
attempts = state.submitCount
const items = entries
.map(([name, messages]) => {
const field = [controller.getField(name)].flat()[0]
return `<li><a href="#${field.id}">${messages[0]}</a></li>`
})
.join('')
controller.append({
tag: 'div',
class: 'error-summary',
atStart: true,
content: `<p role="alert">Fix ${entries.length} problem${entries.length === 1 ? '' : 's'} before publishing:</p><ul>${items}</ul>`,
})
})
controller.onSubmit((_element, data) => {
show('result', `“${data.title}” is published`)
})
return controller
}
const element = document.querySelector('#summary')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = summary(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>List every problem at the top after a failed submit</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="summary" class="demo-form" novalidate aria-labelledby="summary-heading">
<h1 id="summary-heading">List every problem at the top after a failed submit</h1>
<div class="field">
<label for="summary-title">Event title</label>
<input type="text" id="summary-title" name="title" autocomplete="off" />
</div>
<div class="field">
<label for="summary-venue">Venue</label>
<input type="text" id="summary-venue" name="venue" autocomplete="off" />
</div>
<div class="field">
<label for="summary-capacity">Capacity</label>
<input
type="text"
id="summary-capacity"
name="capacity"
autocomplete="off"
inputmode="numeric"
/>
</div>
<div class="actions">
<button type="submit">Publish event</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Problems</dt>
<dd><output data-readout="problems">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const { form } = window.Forms
const summary = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
title: { required: { value: true, message: 'Add an event title.' } },
venue: { required: { value: true, message: 'Say where it happens.' } },
capacity: {
required: { value: true, message: 'Set a capacity.' },
numeric: { value: true, message: 'Capacity must be a number.' },
},
},
})
let attempts = 0
controller.subscribe(state => {
const entries = Object.entries(state.errors)
show('problems', String(entries.length))
if (entries.length === 0) element.querySelector('.error-summary')?.remove()
// Rebuild the summary once per submit attempt, not on every keystroke.
if (state.submitCount === attempts || entries.length === 0) return
attempts = state.submitCount
const items = entries
.map(([name, messages]) => {
const field = [controller.getField(name)].flat()[0]
return `<li><a href="#${field.id}">${messages[0]}</a></li>`
})
.join('')
controller.append({
tag: 'div',
class: 'error-summary',
atStart: true,
content: `<p role="alert">Fix ${entries.length} problem${entries.length === 1 ? '' : 's'} before publishing:</p><ul>${items}</ul>`,
})
})
controller.onSubmit((_element, data) => {
show('result', `“${data.title}” is published`)
})
return controller
}
const element = document.querySelector('#summary')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = summary(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
Package / ESM
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>List every problem at the top after a failed submit</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<main>
<form id="summary" class="demo-form" novalidate aria-labelledby="summary-heading">
<h1 id="summary-heading">List every problem at the top after a failed submit</h1>
<div class="field">
<label for="summary-title">Event title</label>
<input type="text" id="summary-title" name="title" autocomplete="off" />
</div>
<div class="field">
<label for="summary-venue">Venue</label>
<input type="text" id="summary-venue" name="venue" autocomplete="off" />
</div>
<div class="field">
<label for="summary-capacity">Capacity</label>
<input
type="text"
id="summary-capacity"
name="capacity"
autocomplete="off"
inputmode="numeric"
/>
</div>
<div class="actions">
<button type="submit">Publish event</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Problems</dt>
<dd><output data-readout="problems">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module" src="./main.js"></script>
</body>
</html>
CSS
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
JavaScript
import { form } from '@samline/forms'
const summary = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
title: { required: { value: true, message: 'Add an event title.' } },
venue: { required: { value: true, message: 'Say where it happens.' } },
capacity: {
required: { value: true, message: 'Set a capacity.' },
numeric: { value: true, message: 'Capacity must be a number.' },
},
},
})
let attempts = 0
controller.subscribe(state => {
const entries = Object.entries(state.errors)
show('problems', String(entries.length))
if (entries.length === 0) element.querySelector('.error-summary')?.remove()
// Rebuild the summary once per submit attempt, not on every keystroke.
if (state.submitCount === attempts || entries.length === 0) return
attempts = state.submitCount
const items = entries
.map(([name, messages]) => {
const field = [controller.getField(name)].flat()[0]
return `<li><a href="#${field.id}">${messages[0]}</a></li>`
})
.join('')
controller.append({
tag: 'div',
class: 'error-summary',
atStart: true,
content: `<p role="alert">Fix ${entries.length} problem${entries.length === 1 ? '' : 's'} before publishing:</p><ul>${items}</ul>`,
})
})
controller.onSubmit((_element, data) => {
show('result', `“${data.title}” is published`)
})
return controller
}
const element = document.querySelector('#summary')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = summary(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
Complete file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>List every problem at the top after a failed submit</title>
<style>
main {
display: grid;
gap: 1.5rem;
max-width: 32rem;
margin: 2rem auto;
padding: 0 1rem;
font:
1rem/1.6 system-ui,
sans-serif;
}
.demo-form {
display: grid;
gap: 1rem;
padding: 1.5rem;
border: 0.0625rem solid #c3ccd6;
border-radius: 1rem;
}
.demo-form h1 {
margin: 0;
font-size: 1.25rem;
}
.field {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
border: 0;
}
.field label,
.field legend {
font-weight: 600;
}
.field input:not([type='checkbox']),
.field select,
.field textarea {
padding: 0.75rem 0.875rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
font: inherit;
}
.field select,
.demo-form button {
cursor: pointer;
}
.demo-form :focus-visible {
outline: 0.125rem solid #0369a1;
outline-offset: 0.125rem;
}
/* @samline/forms marks fields with the css-error and css-filled attributes. */
.demo-form [css-error] {
border-color: #b42318;
}
[hidden] {
display: none !important;
}
.step {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
}
.step legend {
margin-bottom: 0.5rem;
font-weight: 700;
}
.error-summary {
padding: 0.75rem 1rem;
border: 0.0625rem solid #b42318;
border-radius: 0.5rem;
color: #b42318;
}
.error-summary p,
.error-summary ul {
margin: 0;
}
.error-summary a {
color: inherit;
}
/* Floating labels: the attributes option renamed css-filled and css-error. */
[data-variant='floating'] .field {
position: relative;
}
[data-variant='floating'] .field label {
position: absolute;
top: 0.8rem;
left: 0.9rem;
font-weight: 400;
color: #5b6672;
pointer-events: none;
transition:
transform 0.15s,
font-size 0.15s;
}
[data-variant='floating'] .field input {
padding-top: 1.35rem;
padding-bottom: 0.4rem;
}
[data-variant='floating'] .field:has(:focus, [data-filled]) label {
transform: translateY(-0.6rem);
font-size: 0.75rem;
}
[data-variant='floating'] [data-invalid][data-filled] {
border-color: #b42318;
}
/* Rules that run on load mark empty fields too: wait until they are filled. */
.demo-form[data-errors='filled'] [css-error]:not([css-filled]) {
border-color: #7d8a99;
}
.help,
.error {
margin: 0;
font-size: 0.875rem;
}
.error {
color: #b42318;
}
.error:empty {
display: none;
}
.check {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 400;
}
.row,
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.row input {
flex: 1 1 12rem;
}
.demo-form button {
padding: 0.625rem 1rem;
border: 0.0625rem solid #7d8a99;
border-radius: 0.5rem;
background: #fff;
font: inherit;
}
.demo-form button[type='submit'] {
border-color: #0369a1;
background: #0369a1;
color: #fff;
}
.demo-form button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.readouts {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.25rem 1rem;
margin: 0;
}
.readouts dd {
margin: 0;
font-family: ui-monospace, monospace;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<main>
<form id="summary" class="demo-form" novalidate aria-labelledby="summary-heading">
<h1 id="summary-heading">List every problem at the top after a failed submit</h1>
<div class="field">
<label for="summary-title">Event title</label>
<input type="text" id="summary-title" name="title" autocomplete="off" />
</div>
<div class="field">
<label for="summary-venue">Venue</label>
<input type="text" id="summary-venue" name="venue" autocomplete="off" />
</div>
<div class="field">
<label for="summary-capacity">Capacity</label>
<input
type="text"
id="summary-capacity"
name="capacity"
autocomplete="off"
inputmode="numeric"
/>
</div>
<div class="actions">
<button type="submit">Publish event</button>
</div>
</form>
<dl class="readouts" aria-live="polite">
<dt>Problems</dt>
<dd><output data-readout="problems">—</output></dd>
<dt>Result</dt>
<dd><output data-readout="result">—</output></dd>
</dl>
</main>
<script type="module">
import { form } from '@samline/forms'
const summary = (element, show) => {
const controller = form(element, {
autoValidate: false,
validators: {
title: { required: { value: true, message: 'Add an event title.' } },
venue: { required: { value: true, message: 'Say where it happens.' } },
capacity: {
required: { value: true, message: 'Set a capacity.' },
numeric: { value: true, message: 'Capacity must be a number.' },
},
},
})
let attempts = 0
controller.subscribe(state => {
const entries = Object.entries(state.errors)
show('problems', String(entries.length))
if (entries.length === 0) element.querySelector('.error-summary')?.remove()
// Rebuild the summary once per submit attempt, not on every keystroke.
if (state.submitCount === attempts || entries.length === 0) return
attempts = state.submitCount
const items = entries
.map(([name, messages]) => {
const field = [controller.getField(name)].flat()[0]
return `<li><a href="#${field.id}">${messages[0]}</a></li>`
})
.join('')
controller.append({
tag: 'div',
class: 'error-summary',
atStart: true,
content: `<p role="alert">Fix ${entries.length} problem${entries.length === 1 ? '' : 's'} before publishing:</p><ul>${items}</ul>`,
})
})
controller.onSubmit((_element, data) => {
show('result', `“${data.title}” is published`)
})
return controller
}
const element = document.querySelector('#summary')
const show = (id, text) => {
document.querySelector(`[data-readout="${id}"]`).value = text
}
const controller = summary(element, show)
// A persisted pagehide (back/forward cache) keeps the form working;
// a real departure removes every listener the controller added.
window.addEventListener('pagehide', event => {
if (!event.persisted) controller.destroy()
})
</script>
</body>
</html>
These examples show a few possibilities. The next ideas are yours: combine the package’s capabilities with your own content, design and interactions to create the experience your project needs.
Read the example guideDownload the Forms skill for AI agents