- Docs
- Get started with Forms
Get started with Forms
Install @samline/forms, keep your native form markup and create a controller that validates, reports state and submits clean data.
@samline/forms adds validation, reactive state, serialization and auto-submit to a native <form>. It does not render inputs or messages: your markup stays yours, and one controller listens to it.
Requirements
- Browsers: an ES2020 runtime with
FormData,MutationObserverandrequestSubmit()(current evergreen browsers). The controller falls back to clicking a submit button whenrequestSubmit()is missing. - Node.js 20+ when you install and bundle the package. The DOM-free helpers
validateValues()andvalidateFieldValue()also run in Node;form()needs a browser DOM. - Optional:
@samline/formatterforformat(),formatAll()and theformatsoption. The standalone browser script already includes it.
Install
npm
npm install @samline/formspnpm
pnpm add @samline/formsyarn
yarn add @samline/formsbun
bun add @samline/formsHTML / CDN
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js" defer></script>Your first form
Keep a native form with named fields. Add novalidate so the browser does not stop the submit with its own bubbles before the controller can run your rules.
<form id="signup" novalidate>
<label for="email">Email</label>
<input id="email" name="email" type="email" autocomplete="email" aria-describedby="email-error" />
<p id="email-error" data-error-for="email" aria-live="polite"></p>
<button type="submit">Sign up</button>
</form>
Create one controller for that form. form() accepts an id, an HTMLFormElement or a { current } ref.
import { form } from '@samline/forms'
const signup = form('signup', {
// Stay quiet until the first submit, then revalidate on every input.
autoValidate: false,
validators: {
email: {
required: { value: true, message: 'Enter your email.' },
pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Use a valid email.' },
},
},
})
// The controller marks invalid fields; you decide where messages appear.
signup.subscribe(state => {
document.querySelector('#email-error').textContent = state.errors.email?.[0] ?? ''
})
// Runs only when every rule passes. The browser's navigation is prevented.
signup.onSubmit(async (_element, data, formData) => {
await fetch('/api/signup', { method: 'POST', body: formData })
signup.reset()
})
What happens:
- With
autoValidate: false, rules first run on submit and then on everyinputevent. The default,autoValidate: true, runs them on load as well; seeautoValidate. - Invalid controls receive
css-errorandaria-invalid="true"; filled controls receivecss-filled. Style them as described in Styling with CSS. - An invalid submit is always prevented, handlers do not run, and focus moves to the first invalid control in document order.
- A valid submit passes the serialized object, a fresh
FormDataand a state snapshot to every handler.state.isSubmittingstaystrueuntil a returned promise settles.
Working starter files
These are the files behind the first live example on Home: a sign-up form with four rules, run by the real package. Save HTML, CSS and JavaScript together, or copy the complete file. Choose HTML / CDN to run them without a build step.
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>
HTML / CDN
Without a bundler, load the standalone script. It defines window.Forms with form, newForm, destroyForm and available, and it already contains the formatter.
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js"></script>
<script>
const signup = window.Forms.form('signup', {
validators: { email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ } },
})
</script>
newForm({ id, options }) does the same and stores the controller in Forms.available[id]; destroyForm(id) destroys and removes it. See Browser global and CDN.
Browser registry helpers (bundler)
With a bundler you can use the same { form, newForm, destroyForm, available } shape without loading the standalone script. Import the browser singleton from the root entry; it does not set a global.
import { browser } from '@samline/forms'
const signup = browser.newForm({ id: 'signup', options: { autoValidate: false } })
browser.available.signup === signup // true
browser.destroyForm('signup')
newForm destroys an earlier controller registered under the same id before creating a new one. Spreading browser into your own object shares its registry, so every copy sees the same available map. The @samline/forms/browser subpath exports the same functions and, unlike the root entry, also sets globalThis.Forms.
Ownership and cleanup
A controller owns the listeners, MutationObserver and auto-submit timer it creates for one form. Create it when the form exists in the DOM and call destroy() when the form goes away: on component unmount, on client-side route changes, or never for a form that lives as long as the page.
const controller = form('signup')
// Tie your own listeners or timers to the same lifetime.
const onResize = () => {}
window.addEventListener('resize', onResize)
controller.addCleanup(() => window.removeEventListener('resize', onResize))
// Later:
controller.destroy()
After destroy(), methods remain callable but no longer change the form, so a late callback cannot repaint a form that another controller now owns. Read Framework integrations for React, Vue, Svelte, Astro, Shopify and WordPress lifecycles.
Next steps
- Examples — twelve live forms with their code.
- Validation and errors — every rule, cross-field checks and accessible messages.
- Configuration options — every option and default.
- API reference — every method, grouped by task.