- Docs
- Handle submits with onSubmit()
Handle submits with onSubmit()
Registers a handler that runs when the form is submitted and validation passes. Multiple handlers can be registered; each runs in registration order.
Registers a handler that runs when the form is submitted and validation passes. Multiple handlers can be registered; each runs in registration order.
Signature
onSubmit(
callback: FormSubmitHandler,
preventDefault?: boolean
): FormController
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
callback |
FormSubmitHandler |
yes | — | Handler invoked when the form is valid. Receives (form, data, formData, state). |
preventDefault |
boolean |
no | true |
Whether to intercept valid submissions. Invalid submissions are always intercepted. |
Returns
The same FormController — chainable.
Behaviour
The submit pipeline runs in this order:
- If
clearErrorsOnSubmitistrue(default), manual errors are cleared. - Validation runs for every field with rules.
isValidatedbecomestrue. - If validation fails, the browser’s native submit is prevented, submit handlers are not invoked,
aria-invalid="true"is synchronized, the invalid control that comes first in document order receives focus if it is connected, enabled and not hidden (including the first failingeachmember; since 2.8.0 the order follows the DOM, not the schema). A submit started by auto-submit never moves focus,submitCountis incremented, and subscribers are notified. - If validation passes:
submitCountis incremented.- Subscribers are notified.
- If at least one handler was registered with
preventDefault: true, the native submit is prevented. Otherwise (all handlerspreventDefault: false), the native submit proceeds. - Every registered handler is invoked in registration order. When the event supplies a successful named submit button, its name/value is included in
dataandformData. - Promise-returning handlers are tracked concurrently. Subscribers receive
isSubmitting: truewhile the batch is pending and another update when all promises in it have fulfilled or rejected. A rejected promise is reported withconsole.error('[forms] submit handler failed', reason); catch it inside the handler to show your own message.
Examples
Default: intercept and send with fetch
import { form } from '@samline/forms'
const profile = form('profile-form')
profile.onSubmit(async (_element, _data, formData) => {
await fetch('/profile', { method: 'POST', body: formData })
})
Pass false to allow native submit
import { form } from '@samline/forms'
const bladeForm = form('blade-form', {
validators: { email: { required: true } },
})
bladeForm.onSubmit(() => {
console.log('client-side hooks ran')
}, false)
Use this when you want the browser to perform the native submit (Blade, ERB, classic Rails, etc.) but still run a client-side hook first.
Multiple handlers
profile
.onSubmit((_form, data) => analytics.track('signup', data))
.onSubmit(async (_form, _data, formData) => {
await fetch('/signup', { method: 'POST', body: formData })
})
Edge cases
- Handlers receive a fresh
FormDatabuilt from the live form on each invocation. Do not cache it. datais a plain object mirror ofFormData. Repeated names become arrays (e.g.interests: ['design', 'code']).- Handlers do not receive errors as an argument. If you need to inspect the validation result, read
getState()or callvalidate()from inside the handler. onSubmitcannot be removed — there is nooffSubmitAPI. If you need conditional submission, guard inside the handler or recreate the controller.- Handlers may return
voidorPromise<void>. Invocation still starts synchronously and native submit prevention is decided before promises settle; async resolution does not gate the browser. - Handlers in one submission run concurrently. The controller invokes them in registration order without awaiting between calls, then tracks all returned promises together.
- Rejected promises settle submission state. They do not become form errors and are consumed by the controller’s all-settled tracking, so
isSubmittingreturns tofalsewhen no other submission work remains. - Overlapping submissions are tracked independently.
isSubmittingremainstrueuntil every pending submission batch has settled.
Related
autoSubmit— submit on every change.validate— run validation without submitting.getData— what the handler receives.