form

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package form is a validating form: a column of single-line fields, each with a label and optional validators, and a Submit that checks them all.

It composes textinput, passwordinput (for Secret fields) and focus.Route, so Tab and Shift+Tab move between fields and every other message goes to the focused field only. Submit runs every field's validators, shows each failing field's first error, moves focus to the first invalid field and only when all fields pass emits a SubmittedMsg. An error shown after a failed Submit is re-checked whenever its field is edited and clears once the value validates. Enter submits.

A field is single-line text (masked when Secret), a choice from a list (FieldSelect) or a yes/no box (FieldCheckbox). Every field's value is a string in Values and SubmittedMsg.Values: a select's is its chosen option, a checkbox's is "true" or "false", so one Validator type checks them all.

Model is a value type like the other widgets: Update and Submit return the new Model and leave the receiver unchanged.

Example

A signup form: type into the focused field, Tab to move on, and Submit (or press Enter) to check everything at once. A failed Submit shows the errors and focuses the first invalid field; a valid one yields a SubmittedMsg.

package main

import (
	"fmt"
	"strings"

	"github.com/ows4444/tui"
	"github.com/ows4444/tui/ansi"
	"github.com/ows4444/tui/form"
)

func main() {
	m := form.New(
		form.Field{Name: "email", Label: "Email", Validators: []form.Validator{form.Required(), form.Email()}},
		form.Field{Name: "password", Label: "Password", Secret: true, Validators: []form.Validator{form.Required(), form.MinLen(8)}},
	)
	m.Focus()

	// Submitting an empty form fails and shows the first error of each field.
	m, _ = m.Submit()
	for _, line := range strings.Split(ansi.StripANSI(m.View()), "\n") {
		fmt.Println(strings.TrimRight(line, " ")) // rows are padded for the cursor
	}
	fmt.Println("focused:", m.Current())

	// Fill it in: type, Tab, type.
	for _, r := range "ada@example.com" {
		m, _ = m.Update(tui.Key{Type: tui.KeyRunes, Text: string([]rune{r})})
	}
	m, _ = m.Update(tui.Key{Type: tui.KeyTab})
	for _, r := range "correct horse" {
		m, _ = m.Update(tui.Key{Type: tui.KeyRunes, Text: string([]rune{r})})
	}

	_, cmd := m.Submit()
	msg := cmd().(form.SubmittedMsg)
	fmt.Println("email:", msg.Values["email"])
	fmt.Println("password entered:", len(msg.Values["password"]) > 0)

}
Output:
Email:
  required
Password:
  required
focused: email
email: ada@example.com
password entered: true

Index

Examples

Constants

View Source
const DefaultWidth = 30

DefaultWidth is the visible width of a field whose Width is 0.

Variables

This section is empty.

Functions

This section is empty.

Types

type Field

type Field struct {
	Name  string // key in Values and SubmittedMsg.Values; keep names unique
	Label string // shown before the input
	// Kind is how the field is drawn and edited; the zero value is FieldText.
	Kind FieldKind
	// Options are the choices of a FieldSelect, in order. Ignored otherwise.
	Options []string
	// Placeholder is shown while a text field is empty. Text fields only.
	Placeholder string
	// Value is the initial value: the text of a text field, the chosen option
	// of a select (an unknown or empty value chooses the first option), or
	// "true" (in any case) for a ticked checkbox; anything else is unticked.
	Value string
	// Secret masks a text field's value and never speaks it. Text fields only.
	Secret bool
	// Width is a text field's visible width; 0 = DefaultWidth. Text fields only.
	Width      int
	Validators []Validator
}

Field describes one form field.

type FieldKind

type FieldKind int

FieldKind selects how a Field is drawn and edited.

const (
	// FieldText is a single-line text field, masked when Field.Secret is set.
	// It is the zero value, so a Field that sets no Kind is a text field.
	FieldText FieldKind = iota
	// FieldSelect is a choice from Field.Options: Left and Up choose the
	// previous option, Right and Down the next, stopping at either end. Its
	// value is the chosen option.
	FieldSelect
	// FieldCheckbox is a yes/no box: Space toggles it. Its value is "true" or
	// "false".
	FieldCheckbox
)

type KeyMap

type KeyMap struct {
	Submit     keymap.Binding // check every field and submit
	SelectPrev keymap.Binding // choose the previous option of a select
	SelectNext keymap.Binding // choose the next option of a select
	Toggle     keymap.Binding // tick or untick a checkbox
}

KeyMap names the keys of each action of a Model.

func DefaultKeyMap

func DefaultKeyMap() KeyMap

DefaultKeyMap returns the keys a Model used before KeyMap existed.

type Model

type Model struct {
	// Theme colors the error lines. New sets theme.DarkTheme().
	Theme theme.Theme

	// KeyMap holds the keys for submitting and for editing select and
	// checkbox fields. New fills it with DefaultKeyMap; a Model with a zero
	// KeyMap behaves as if it held DefaultKeyMap. Tab and Shift+Tab move
	// between fields through focus.Route and are not rebindable here.
	KeyMap KeyMap

	// Mouse, when true, makes a focused form's Update handle tui.MouseEvent: a
	// left click on a field focuses it; on a checkbox it also toggles it, on a
	// select it chooses the previous option (left of the option's middle) or
	// the next one (right of it). The wheel over a select chooses the previous
	// or next option. Off (the default) ignores the mouse.
	Mouse bool
	// Bounds is the screen rectangle where the app draws the form (its first
	// row is the first field); mouse events outside it are ignored.
	Bounds hittest.Rect
	// contains filtered or unexported fields
}

Model is a form. Build one with New.

func New

func New(fields ...Field) Model

New returns a form of the given fields. It is not focused: call Focus.

func (Model) Bindings

func (m Model) Bindings() []keymap.Binding

Bindings returns the actions active for the field that has focus, with descriptions, for help text: Submit, the fixed Tab and Shift+Tab field movement, then the focused field's own keys (an option choice for a select, Toggle for a checkbox, the editing keys of its input for a text field).

func (*Model) Blur

func (m *Model) Blur()

Blur removes focus from the form and every field.

func (Model) Current

func (m Model) Current() string

Current returns the Name of the field that has focus within the form, or "" for a form with no fields.

func (Model) Err

func (m Model) Err(name string) string

Err returns the error currently shown for the field called name, or "".

func (*Model) Focus

func (m *Model) Focus() tui.Cmd

Focus focuses the form, and the field that has focus within it, returning the Cmd that field needs (its cursor blink). Run the Cmd.

func (Model) Focused

func (m Model) Focused() bool

Focused reports whether the form has focus.

func (Model) LayoutNode

func (m Model) LayoutNode() layout.Node

LayoutNode adapts the form to a layout.Node. Measure reports one row per field plus one for each error showing, as wide as the widest of them. Render draws exactly the Size given: each field's input at the full width (a Secret field through its masking node, so its value is never drawn) and each error on the row below it. When there are more rows than Size.H, the window follows the focused field so it stays visible, rather than clipping to the top. The Model is not changed.

func (Model) Linearize

func (m Model) Linearize() string

Linearize renders the form as plain text for accessible output (see tui.Linearizer): one line per field, in order. Each line is that field's own description (its label, kind, ", focused" when it has focus, and its value, a select's option and position, or a checkbox's checked state) followed by ", error: <message>" when the field has an error showing. A Secret field is a passwordinput, so it speaks only how many characters were entered, never the value. The error text is spoken as written, so a validator must not put a secret into its message.

func (Model) SetTheme

func (m Model) SetTheme(t theme.Theme) Model

SetTheme returns m with t applied. It makes Model a tui.ThemeSetter, so a root model can forward the Program's theme (see tui.WithTheme).

func (Model) Submit

func (m Model) Submit() (Model, tui.Cmd)

Submit checks every field. If any fails, each failing field shows its first error, focus moves to the first invalid field and no SubmittedMsg is produced. If all pass, the returned Cmd yields a SubmittedMsg with the values.

func (Model) Tokens

func (m Model) Tokens() theme.Tokens

Tokens returns the colour tokens the widget renders with: its theme's roles, overridden by any theme.WithTokens(theme.ComponentForm, ...) and then by WithTokens.

func (Model) Update

func (m Model) Update(msg tui.Msg) (Model, tui.Cmd)

Update routes msg. Tab and Shift+Tab move focus between fields, Enter submits, and every other message goes to the focused field, after which that field's error, if one is showing, is re-checked. With Mouse on it also handles tui.MouseEvent (see Model.Mouse). A form without focus ignores all messages.

func (Model) Values

func (m Model) Values() map[string]string

Values returns each field's current value, keyed by Name. A Secret field's real value is included: it is what the application asked for.

func (Model) View

func (m Model) View() string

View renders each field on its own line, followed by its error, if any, on the next line.

func (Model) WithTokens

func (m Model) WithTokens(tok theme.Tokens) Model

WithTokens returns m with tok as its per-instance colour override. Nil fields inherit from the theme, so only the roles tok names change; the theme and every other widget are untouched. A second call replaces the first.

type SubmittedMsg

type SubmittedMsg struct {
	Values map[string]string
}

SubmittedMsg is the message Submit's Cmd yields when every field is valid.

type Validator

type Validator func(value string) error

Validator checks one field's value and returns an error describing what is wrong, or nil. The error's text is what the form shows.

func Email

func Email() Validator

Email rejects a non-empty value that is not a plain address such as name@example.com: it must parse as an address with nothing else around it and a dotted domain. It is a pragmatic check, not full RFC 5322.

func Match

func Match(re *regexp.Regexp, msg string) Validator

Match rejects a non-empty value that re does not match, with msg as the error text. It panics if re is nil.

func MaxLen

func MaxLen(n int) Validator

MaxLen rejects a value longer than n characters (runes).

func MinLen

func MinLen(n int) Validator

MinLen rejects a non-empty value shorter than n characters (runes).

func Required

func Required() Validator

Required rejects an empty or all-whitespace value. It is the only built-in validator that rejects an empty value: the others pass it, so a field can be optional but well-formed when filled in. Pair them with Required to demand a value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL