Form: validate named controls as a Go struct
kitex.Form collects named controls and passes a map[string]any to OnSubmit. Use extras/form when the rest of your program should receive a typed value. You don’t need a state setter for each keystroke.
Match controls to fields
Section titled “Match controls to fields”Give each control a Name and match it to an exported field. An explicit form tag names the key; otherwise the decoder tries a json tag, then the field name (case-insensitive). Return errors under the control name, not the Go field name. An empty map or nil passes validation.
type Draft struct { Title string `form:"title"` Pinned bool `form:"pinned"`}
func check(d Draft) map[string]string { if strings.TrimSpace(d.Title) == "" { return map[string]string{"title": "Enter a title"} } return nil}| Control | Value to decode |
|---|---|
Input, TextArea |
Text, usually a string. For numeric fields the text must parse as that type. |
Checkbox |
A bool, including false when unchecked. |
Radio |
Only the checked radio contributes its value. Wrap Radio choices in an enclosing RadioGroup (which owns selection and reset) and give each Radio the same Name. |
Select |
The selected option’s value, not its display label. |
Wire decoding and submission
Section titled “Wire decoding and submission”Call form.Use during render. Attach its ref to the form, not an input, and pass the handler returned by HandleSubmit to OnSubmit:
type DraftEditorProps struct { Save func(Draft) error}
var DraftEditor = kitex.FC("DraftEditor", func(p DraftEditorProps) kitex.Node { initial := Draft{Title: "Review notes"} f := form.Use(form.Options[Draft]{ InitialValues: initial, Validate: validateDraft, }) s := f.State()
formStyle := demo.Default.Container. Display(style.DisplayFlex). FlexDirection(style.FlexColumn). Gap(1, 0)
labelStyle := demo.Default.ButtonRow. Foreground(demo.Default.Colors.Text)
return kitex.Form( kitex.FormProps{ Ref: f.Ref, OnSubmit: f.HandleSubmit(p.Save), Style: formStyle, }, kitex.Box.Style( demo.Default.ButtonRow, kitex.Input(kitex.InputProps{ Name: "title", Value: initial.Title, Style: demo.Default.Input.Width(style.Cells(22)), }), kitex.Label( kitex.LabelProps{Style: labelStyle}, kitex.Checkbox(kitex.CheckboxProps{ Name: "pinned", Checked: initial.Pinned, }), kitex.Text("Pinned"), ), ), kitex.If(s.Errors["title"] != "", func() kitex.Node { return kitex.Box.Style( demo.Default.StatusWarn, kitex.Text(s.Errors["title"]), ) }), kitex.Box.Style( demo.Default.ButtonRow, kitex.Button(kitex.ButtonProps{ Style: demo.Default.PrimaryButton, Type: "submit", Disabled: s.IsSubmitting, }, kitex.Text("Save")), kitex.Button(kitex.ButtonProps{ Style: demo.Default.Button, Type: "reset", }, kitex.Text("Discard edits")), ), kitex.If(s.Errors["root"] != "", func() kitex.Node { return kitex.Box.Style( style.S().Foreground(demo.Default.Colors.Warn), kitex.Text(s.Errors["root"]), ) }), )})InitialValues seeds hook state; pass matching defaults to the controls so they show the same draft. The submit button decodes into a new Draft: an absent control leaves its field at the zero value, not the initial value. Save runs only after decoding and validation succeed. The reset button restores control defaults and, with the ref attached, resets hook state too.
Validation modes, dirty and touched state
Section titled “Validation modes, dirty and touched state”Set Mode in form.Options[Draft]. All modes validate on submit; the ref enables validation before submit:
| Mode | When the user sees validation errors |
|---|---|
form.ValidateOnSubmit (default) |
On submission, not while editing. |
form.ValidateOnBlur |
When a named control loses focus. Blur shows errors only for touched fields and "root"; submission validates and shows all errors. |
form.ValidateOnChange |
On input or change, including errors in other fields. |
With Ref: f.Ref, f.State().Values follows the controls, an edit sets IsDirty, and leaving a control sets Touched[name]. Editing back to the original value doesn’t clear the dirty flag. IsValid reflects the current errors; it starts true, not as the result of a validation pass. SubmitCount includes invalid attempts and works even without the ref.
Reset and control errors
Section titled “Reset and control errors”Use a field key for a problem the user can fix in one control. Decode failures and errors returned by the save callback go under "root". These helpers are for event handlers, not render:
func discard(f form.API[Draft], next *Draft) { if next == nil { f.Reset() } else { f.Reset(*next) }}
func reportTitleConflict(f form.API[Draft]) { f.ClearErrors("root") f.SetError("title", "That title is already taken")}Reset() restores InitialValues; passing a draft restores that value instead. Both clear errors, touched fields, dirty state, and the submission count. With the ref, reset also updates the mounted controls without replacing them. Without it, state reset, submission, and error handling still work. ClearErrors() clears all messages; pass one or more keys to clear only those. SetError(key, "") clears a single message.
Async submissions (HandleSubmitAsync)
Section titled “Async submissions (HandleSubmitAsync)”For a remote write, use this adapter instead of f.HandleSubmit(p.Save). The caller supplies a save operation that accepts a context:
func asyncSubmit(f form.API[Draft], save func(context.Context, Draft) error) func(map[string]any) { return f.HandleSubmitAsync(func(ctx context.Context, d Draft) error { return save(ctx, d) })}Pass asyncSubmit(f, save) as OnSubmit. Decoding and validation still happen before the worker starts. IsSubmitting stays true across frames until the write finishes, so the same Save button can show it’s busy. Duplicate submits are ignored while a write is pending. Reset or unmount cancels ctx; pass it through to the request so the work can stop. An error from an active write appears under "root"; a canceled write’s late result is ignored.