Native forms. Typed control.

Forms
Send only what’s right.

Forms that check themselves. Validation, reactive state, serialization and auto-submit for native HTML forms, with a typed, framework-free API.
Check a sign-up, format a phone number, or filter a catalog as it changes.

npm install @samline/forms

Native HTML formsJavaScript & TypeScriptMIT licensed

Forms studio
ValidationLive preview

Check a sign-up form before it is sent

form(element, { autoValidate: false, validators })

At least 8 characters, including a number.

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.

FormattingLive preview

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.

Auto-submitLive preview

Filter a catalog as soon as the visitor changes an option

form(element, { autoSubmit: { debounce: 250 } }).prefill()
Only show
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.

ONE CONTROLLER. RIGHT AT HOME IN YOUR STACK.

JavaScript TypeScript React Vue Svelte Astro Shopify WordPress
01 / More than a submit handler

Your native form.
A controller that listens.

Your markup. Your backend.

Bind any <form> by id, element or ref. Fields keep their names, and the FormData your server reads stays the same.

Errors people can find

Invalid controls get aria-invalid, and a failed submit focuses the first one in document order. You write the messages and decide where they appear.

Create. Listen. Destroy.

One controller owns its listeners, observer and timers. destroy() releases them, including the cleanups you register.

Rules instead of boilerplate

Required, length, pattern and numeric bounds, matching fields, dependencies, per-row rules and custom validators that read every value.

State you can subscribe to

Values, errors, filled fields and submission status arrive in one snapshot, ready for any UI layer.

Formatted for people, clean for servers

Phones, cards, dates and amounts format as people type, while a hidden field submits the raw value under the original name.

02 / Fit it into your stack

Two ways in. One form() call.

Import from npm or load one script tag. The controller is the same in both; only the standalone script and the /browser subpath set a Forms global.

Package / ESM

@samline/forms

form(), createFormController() and the DOM-free helpers parseFormData, validateValues and validateFieldValue, with TypeScript declarations. CommonJS is also exported.

Registry helpers

@samline/forms/browser

newForm({ id }), destroyForm(id) and the available map keep one controller per form id. Importing this subpath also sets globalThis.Forms.

HTML / CDN

window.Forms

The standalone script already contains @samline/formatter, so formatting works without a build step. Pin the version in production.

Optional peer

@samline/formatter

Install it beside the package to use format(), formatAll() and the formats option. Without it those calls log one error and the form keeps working.

Types

FormController · ValidationSchema

Every option, rule, snapshot and callback has an exported type. Use satisfies ValidationSchema for reusable rule sets.

Styles

css-filled · css-error

No stylesheet to import. Style the attributes the controller toggles, or rename them with the attributes option.

03 / From install to a checked submit

One form. One controller.

Install the package, keep your form markup, then create a controller with the rules it should enforce. Copy a complete example when you want a setup without a bundler.

Read the installation guide
1

Install

npm

Terminal
npm install @samline/forms

pnpm

Terminal
pnpm add @samline/forms

yarn

Terminal
yarn add @samline/forms

bun

Terminal
bun add @samline/forms

HTML / CDN

Terminal
<script src="https://cdn.jsdelivr.net/npm/@samline/forms@3.0.0/dist/browser/forms.global.js" defer></script>
2

Add a form

A native form with named fields. novalidate lets the controller’s rules and messages replace the browser’s bubbles.

index.html
<form id="signup" novalidate>
  <label for="email">Email</label>
  <input id="email" name="email" type="email" autocomplete="email">
  <p data-error-for="email" aria-live="polite"></p>
  <button type="submit">Sign up</button>
</form>
3

Create the controller

main.js
import { form } from '@samline/forms'

const signup = form('signup', {
  autoValidate: false,
  validators: {
    email: {
      required: { value: true, message: 'Enter your email.' },
      pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Use a valid email.' },
    },
  },
})

signup.subscribe(state => {
  document.querySelector('[data-error-for="email"]').textContent =
    state.errors.email?.[0] ?? ''
})

signup.onSubmit(async (_element, data, formData) => {
  await fetch('/api/signup', { method: 'POST', body: formData })
  signup.reset()
})
// When the page or component goes away:
// signup.destroy()
Copy complete working files

Every option, rule and default is in the configuration reference.

Explore the configuration reference
04 / After the first submit

After the first submit.
Keep every field in sync.

Three patterns most forms need next. Each one uses the same controller you already created.

Validation

Print each message beside its field

One subscriber receives every change. Render the first error of each field and disable the button while a submit is pending.

Read the validation guide
main.js
const controller = form('checkout', { autoValidate: false, validators })

controller.subscribe(state => {
  for (const slot of document.querySelectorAll('[data-error-for]')) {
    slot.textContent = state.errors[slot.dataset.errorFor]?.[0] ?? ''
  }
  submitButton.disabled = state.isSubmitting
})
Server errors

Attach the server’s answer

Pass the field errors your API returns to setErrors(). They mark the fields like local rules and clear as soon as the visitor edits them.

Read about manual errors
main.js
controller.onSubmit(async (_element, _data, formData) => {
  const response = await fetch('/api/account', { method: 'POST', body: formData })
  if (response.status === 422) {
    // { "username": ["That username is already taken."] }
    controller.setErrors(await response.json())
  }
})
Auto-submit

Restore filters from a link

Auto-submit after a short pause, keep the query string in the address bar, and prefill the same form when someone opens the link.

Read about state and submission
main.js
const filters = form('filters', { autoSubmit: { debounce: 250 } })

filters.onSubmit((_element, _data, formData) => {
  const query = new URLSearchParams(formData)
  history.replaceState(null, '', `?${query}`)
  renderProducts(query)
})

// ?category=decor&tags[]=sale restores the same filters.
filters.prefill()
Explore working examples
05 / Before you build

A few details. Clearly answered.

Why add novalidate to the form?
Without it, the browser checks type="email", required and similar attributes before the submit event fires, shows its own bubble and stops the submit. novalidate makes the controller’s rules and your messages the single source of truth.
What does my server receive?
The native form’s FormData, including the button that submitted it. Empty file inputs are skipped. A formatted field sends the raw value under its original name and the formatted text as <name>_displayed.
Does the package render error messages?
No. It sets css-error and aria-invalid on invalid controls and moves focus after a failed submit. Read state.errors in subscribe() and place each message where your design needs it, ideally linked with aria-describedby.
Can I use it with React, Vue or Svelte?
Yes, as a DOM controller: create it after the form mounts and call destroy() before it unmounts. Keep the form uncontrolled, or write values with setValue() so the controller hears the change. There are no framework adapters.
Can I use it without a bundler?
Load dist/browser/forms.global.js from a CDN or your own server. It defines window.Forms with form, newForm, destroyForm and available, and it already includes the formatter.
Do I need @samline/formatter?
Only for format(), formatAll() and the formats option with npm installs. It is an optional peer: validation, state and serialization work without it.
What happens when fields are added or removed?
The controller observes the form and revalidates when controls are added, removed or renamed. Name repeated inputs with [] to read them as a list and use each rules to check every row.
How do I handle asynchronous submits?
Return a promise from onSubmit(). state.isSubmitting stays true until every handler settles; a rejected handler is reported in the console. Use it to disable the button and prevent double submits.
Can I run the same rules on the server?
validateValues() and validateFieldValue() are pure and DOM-free, so the same ValidationSchema runs in Node 20+. form() itself needs a browser DOM.
How are changes documented?
CHANGELOG.md is the single release history and labels behavior changes. Docs, examples and the agent skill are updated with each release.
Native forms, checked before they leave

Make every submit a valid one.

Try a live form or follow the first steps.

Guides, the complete API and verified release notes, in one place.

Read the documentation