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.
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/formsNative HTML formsJavaScript & TypeScriptMIT licensed
Check a sign-up form before it is sent
form(element, { autoValidate: false, validators })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.
Format phone, card and amount fields while sending clean values
form(element, { formats: { phone: { type: 'phone', field: 'phone' } } })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.
Filter a catalog as soon as the visitor changes an option
form(element, { autoSubmit: { debounce: 250 } }).prefill()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.
Bind any <form> by id, element or ref. Fields keep their names, and the FormData your server reads stays the same.
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.
One controller owns its listeners, observer and timers. destroy() releases them, including the cleanups you register.
Required, length, pattern and numeric bounds, matching fields, dependencies, per-row rules and custom validators that read every value.
Values, errors, filled fields and submission status arrive in one snapshot, ready for any UI layer.
Phones, cards, dates and amounts format as people type, while a hidden field submits the raw value under the original name.
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
form(), createFormController() and the DOM-free helpers parseFormData, validateValues and validateFieldValue, with TypeScript declarations. CommonJS is also exported.
Registry helpers
newForm({ id }), destroyForm(id) and the available map keep one controller per form id. Importing this subpath also sets globalThis.Forms.
HTML / CDN
The standalone script already contains @samline/formatter, so formatting works without a build step. Pin the version in production.
Optional peer
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
Every option, rule, snapshot and callback has an exported type. Use satisfies ValidationSchema for reusable rule sets.
Styles
No stylesheet to import. Style the attributes the controller toggles, or rename them with the attributes option.
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 guideInstall
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>Add a form
A native form with named fields. novalidate lets the controller’s rules and messages replace the browser’s bubbles.
<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>Create the controller
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()Every option, rule and default is in the configuration reference.
Explore the configuration referenceThree patterns most forms need next. Each one uses the same controller you already created.
One subscriber receives every change. Render the first error of each field and disable the button while a submit is pending.
Read the validation guideconst 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
})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 errorscontroller.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 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 submissionconst 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()Try a live form or follow the first steps.
Guides, the complete API and verified release notes, in one place.
Read the documentation