- Docs
- Serialize any form with parseFormData()
Serialize any form with parseFormData()
Pure serializer that returns a plain object mirror of a form plus a fresh FormData, skipping empty file inputs and honoring the submitter.
Pure serializer. Returns a plain object mirror of the form plus a fresh FormData instance. Does not require a controller — useful for one-off serialization (e.g. server-side hydration, scripts that read forms outside of a binding).
Signature
function parseFormData(
formElement: HTMLFormElement,
submitter?: HTMLElement | null
): SerializedFormResult
interface SerializedFormResult {
data: Record<string, SerializedFormValue>
formData: FormData
}
type SerializedFormValue = FormDataPrimitive | FormDataPrimitive[]
type FormDataPrimitive = FormDataEntryValue // string | File
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
formElement |
HTMLFormElement |
yes | The form to serialize. |
submitter |
HTMLElement | null |
no | Successful named submit button whose contribution should be included. |
Returns
A SerializedFormResult with two fresh values:
data— plain object mirror. Repeated names become arrays.formData— a freshFormDatainstance.
Behaviour
- Reads directly from the live DOM via
new FormData(formElement, submitter)when a submitter is supplied. - Preserves fields named
constructoror__proto__as ordinary own properties indata. - Drops entries where the value is an empty
File(size === 0andname === ''). - Builds the
datamirror while iterating, grouping repeated names into arrays. - Does not mutate the form or any global state.
Examples
One-off serialization
import { parseFormData } from '@samline/forms'
const formElement = document.querySelector<HTMLFormElement>('#contact-form')
if (formElement) {
const { data, formData } = parseFormData(formElement)
console.log(data, formData)
}
Hydrate from a snapshot
import { parseFormData } from '@samline/forms'
const element = document.querySelector<HTMLFormElement>('#profile-form')
// Snapshot on every input:
element?.addEventListener('input', () => {
if (!element) return
const { data } = parseFormData(element)
localStorage.setItem('draft', JSON.stringify(data))
})
// Restore on load:
const saved = localStorage.getItem('draft')
if (saved && element) {
const data = JSON.parse(saved) as Record<string, string>
for (const [key, value] of Object.entries(data)) {
const field = element.querySelector<HTMLInputElement>(`[name="${key}"]`)
if (field) field.value = value
}
}
Edge cases
- Empty file inputs are filtered out. This matches what
getData()does inside a controller. parseFormDatadoes not validate — pass the result throughvalidateValuesif you need validation.- No type coercion. All values come from
FormDatadirectly.
Related
getData— controller-bound equivalent.validateValues— run validation against aFormValuesmap.