forms

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package forms provides form state management and validation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AsyncFormValidator

type AsyncFormValidator interface {
	ValidateAsync(ctx context.Context, values Values) []ValidationError
}

AsyncFormValidator validates multiple fields asynchronously.

func AsyncForm

func AsyncForm(fn func(ctx context.Context, values Values) []ValidationError) AsyncFormValidator

AsyncForm wraps a function into an AsyncFormValidator.

type AsyncValidator

type AsyncValidator interface {
	ValidateAsync(ctx context.Context, value any) *ValidationError
}

AsyncValidator validates a field value asynchronously.

func Async

func Async(fn func(ctx context.Context, value any) *ValidationError) AsyncValidator

Async wraps a function into an AsyncValidator.

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder constructs forms using a fluent DSL.

func NewBuilder

func NewBuilder() *Builder

NewBuilder creates a new form builder.

func (*Builder) AsyncValidator

func (b *Builder) AsyncValidator(validator AsyncFormValidator) *Builder

AsyncValidator adds a form-level async validator.

func (*Builder) Build

func (b *Builder) Build() (*Form, []FieldSpec)

Build constructs a Form and returns the field specs used.

func (*Builder) Checkbox

func (b *Builder) Checkbox(name, label string, initial bool, validators ...Validator) *Builder

Checkbox adds a boolean field.

func (*Builder) Date

func (b *Builder) Date(name, label string, initial any, validators ...Validator) *Builder

Date adds a date field.

func (*Builder) Email

func (b *Builder) Email(name, label, initial string, validators ...Validator) *Builder

Email adds an email field.

func (*Builder) Field

func (b *Builder) Field(spec FieldSpec) *Builder

Field adds a custom field spec.

func (*Builder) MultiSelect

func (b *Builder) MultiSelect(name, label string, options []string, initial []string, validators ...Validator) *Builder

MultiSelect adds a multi-select field.

func (*Builder) Number

func (b *Builder) Number(name, label string, initial float64, validators ...Validator) *Builder

Number adds a numeric field (float64).

func (*Builder) Password

func (b *Builder) Password(name, label, initial string, validators ...Validator) *Builder

Password adds a password field.

func (*Builder) Select

func (b *Builder) Select(name, label string, options []string, initial string, validators ...Validator) *Builder

Select adds a single-choice select field.

func (*Builder) Text

func (b *Builder) Text(name, label, initial string, validators ...Validator) *Builder

Text adds a text field.

func (*Builder) Time

func (b *Builder) Time(name, label string, initial any, validators ...Validator) *Builder

Time adds a time field.

func (*Builder) Validator

func (b *Builder) Validator(validator FormValidator) *Builder

Validator adds a form-level validator.

type Field

type Field interface {
	Name() string
	Value() any
	SetValue(any)

	Dirty() bool
	Touched() bool
	Valid() bool
	Errors() []string

	Validate() []ValidationError
	Reset()
}

Field represents a form field.

type FieldBase

type FieldBase struct {
	// contains filtered or unexported fields
}

FieldBase provides common field state management.

func NewFieldBase

func NewFieldBase(name string, initial any, validators ...Validator) *FieldBase

NewFieldBase constructs a field base.

func (*FieldBase) AsyncValidators

func (f *FieldBase) AsyncValidators() []AsyncValidator

AsyncValidators returns a copy of async validators.

func (*FieldBase) Dirty

func (f *FieldBase) Dirty() bool

Dirty reports whether the field value differs from its initial value.

func (*FieldBase) Errors

func (f *FieldBase) Errors() []string

Errors returns the current validation errors.

func (*FieldBase) MarkTouched

func (f *FieldBase) MarkTouched()

MarkTouched marks the field as touched.

func (*FieldBase) Name

func (f *FieldBase) Name() string

Name returns the field name.

func (*FieldBase) ResetState

func (f *FieldBase) ResetState()

ResetState clears dirty/touched/errors.

func (*FieldBase) SetAsyncValidators

func (f *FieldBase) SetAsyncValidators(validators ...AsyncValidator)

SetAsyncValidators updates async validators.

func (*FieldBase) SetErrors

func (f *FieldBase) SetErrors(messages []string)

SetErrors updates the error list.

func (*FieldBase) SetInitial

func (f *FieldBase) SetInitial(value any)

SetInitial updates the initial value used for dirty tracking.

func (*FieldBase) SetValidators

func (f *FieldBase) SetValidators(validators ...Validator)

SetValidators updates the validators.

func (*FieldBase) Touched

func (f *FieldBase) Touched() bool

Touched reports whether the field has been modified.

func (*FieldBase) UpdateDirty

func (f *FieldBase) UpdateDirty(value any)

UpdateDirty updates dirty state based on the provided value.

func (*FieldBase) Valid

func (f *FieldBase) Valid() bool

Valid reports whether the field has no validation errors.

func (*FieldBase) ValidateValue

func (f *FieldBase) ValidateValue(value any) []ValidationError

ValidateValue validates a value using the field validators.

func (*FieldBase) Validating

func (f *FieldBase) Validating() bool

Validating reports whether async validation is running.

func (*FieldBase) ValidatingSignal

func (f *FieldBase) ValidatingSignal() *state.Signal[bool]

ValidatingSignal returns the async validation signal.

type FieldSpec

type FieldSpec struct {
	Name            string
	Label           string
	Type            FieldType
	Placeholder     string
	Options         []string
	Initial         any
	Validators      []Validator
	AsyncValidators []AsyncValidator
	DependsOn       []string
}

FieldSpec describes a form field for builders and renderers.

type FieldType

type FieldType string

FieldType identifies a form field type.

const (
	FieldText        FieldType = "text"
	FieldNumber      FieldType = "number"
	FieldEmail       FieldType = "email"
	FieldPassword    FieldType = "password"
	FieldCheckbox    FieldType = "checkbox"
	FieldSelect      FieldType = "select"
	FieldMultiSelect FieldType = "multiselect"
	FieldDate        FieldType = "date"
	FieldTime        FieldType = "time"
)

type Form

type Form struct {
	// contains filtered or unexported fields
}

Form manages a collection of fields.

func NewForm

func NewForm(fields ...Field) *Form

NewForm constructs an empty form.

func (*Form) AddAsyncValidator

func (f *Form) AddAsyncValidator(validator AsyncFormValidator)

AddAsyncValidator registers an async cross-field validator.

func (*Form) AddField

func (f *Form) AddField(field Field)

AddField registers a field.

func (*Form) AddValidator

func (f *Form) AddValidator(validator FormValidator)

AddValidator registers a cross-field validator.

func (*Form) Cancel

func (f *Form) Cancel()

Cancel invokes the cancel callback.

func (*Form) DirtySignal

func (f *Form) DirtySignal() *state.Signal[bool]

DirtySignal returns the form dirty signal.

func (*Form) Field

func (f *Form) Field(name string) Field

Field returns a field by name.

func (*Form) Get

func (f *Form) Get(name string) any

Get retrieves a field value.

func (*Form) OnCancel

func (f *Form) OnCancel(fn func())

OnCancel sets the cancel callback.

func (*Form) OnSubmit

func (f *Form) OnSubmit(fn func(values Values))

OnSubmit sets the submit callback.

func (*Form) Reset

func (f *Form) Reset()

Reset resets all fields to their initial values.

func (*Form) Set

func (f *Form) Set(name string, value any)

Set updates a field value.

func (*Form) SetDependencies

func (f *Form) SetDependencies(field string, deps ...string)

SetDependencies declares that a field depends on other fields.

func (*Form) Submit

func (f *Form) Submit()

Submit validates and invokes the submit callback.

func (*Form) SubmitAsync

func (f *Form) SubmitAsync(ctx context.Context) <-chan []ValidationError

SubmitAsync runs validation asynchronously and invokes onSubmit if valid.

func (*Form) SubmittingSignal

func (f *Form) SubmittingSignal() *state.Signal[bool]

SubmittingSignal returns the form submitting signal.

func (*Form) ValidSignal

func (f *Form) ValidSignal() *state.Signal[bool]

ValidSignal returns the form valid signal.

func (*Form) Validate

func (f *Form) Validate() []ValidationError

Validate validates all fields and form validators.

func (*Form) ValidateAsync

func (f *Form) ValidateAsync(ctx context.Context) <-chan []ValidationError

ValidateAsync validates fields and async validators, returning a channel of errors.

func (*Form) ValidatingSignal

func (f *Form) ValidatingSignal() *state.Signal[bool]

ValidatingSignal returns the async validating signal.

func (*Form) Values

func (f *Form) Values() Values

Values returns a snapshot of form values.

type FormValidator

type FormValidator interface {
	Validate(values Values) []ValidationError
}

FormValidator validates multiple fields at once.

func FieldsMatch

func FieldsMatch(a, b, msg string) FormValidator

FieldsMatch validates that two fields are equal.

type SimpleField

type SimpleField struct {
	*FieldBase
	// contains filtered or unexported fields
}

SimpleField is a basic field implementation storing its own value.

func NewField

func NewField(name string, initial any, validators ...Validator) *SimpleField

NewField creates a new simple field.

func (*SimpleField) Reset

func (f *SimpleField) Reset()

Reset restores the initial value.

func (*SimpleField) SetValue

func (f *SimpleField) SetValue(value any)

SetValue updates the value and dirty state.

func (*SimpleField) Validate

func (f *SimpleField) Validate() []ValidationError

Validate runs validation on the current value.

func (*SimpleField) ValidateAsync

func (f *SimpleField) ValidateAsync(ctx context.Context) <-chan []ValidationError

ValidateAsync runs async validators and updates errors when complete.

func (*SimpleField) Value

func (f *SimpleField) Value() any

Value returns the current value.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError describes a validation failure.

type Validator

type Validator interface {
	Validate(value any) *ValidationError
}

Validator validates a field value.

func All

func All(validators ...Validator) Validator

All requires all validators to pass.

func AlphaNumeric

func AlphaNumeric(msg string) Validator

AlphaNumeric ensures the value contains only letters and digits.

func And

func And(validators ...Validator) Validator

And requires all validators to pass. It is an alias for All.

func Any

func Any(validators ...Validator) Validator

Any passes if any validator passes.

func ConditionalRequired

func ConditionalRequired(condition func() bool, msg string) Validator

ConditionalRequired requires a non-empty value only when the condition returns true.

func Custom

func Custom(fn func(any) *ValidationError) Validator

Custom wraps a validator function.

func Email

func Email(msg string) Validator

Email validates a simple email format.

func JSON

func JSON() Validator

JSON validates that the value is valid JSON.

func Length

func Length(n int, msg string) Validator

Length enforces an exact length.

func MatchField

func MatchField(other Field, msg string) Validator

MatchField validates that this field's value matches another field's current value. It reads the other field's value at validation time via other.Value().

func Max

func Max(n float64, msg string) Validator

Max enforces a maximum numeric value.

func MaxLength

func MaxLength(n int, msg string) Validator

MaxLength enforces a maximum length.

func Min

func Min(n float64, msg string) Validator

Min enforces a minimum numeric value.

func MinLength

func MinLength(n int, msg string) Validator

MinLength enforces a minimum length.

func Not

func Not(v Validator, msg string) Validator

Not inverts a validator: it fails when the wrapped validator passes and vice versa.

func Numeric

func Numeric(msg string) Validator

Numeric ensures the value contains only digits.

func OneOf

func OneOf(values ...string) Validator

OneOf ensures the value matches one of the allowed strings.

func Or

func Or(validators ...Validator) Validator

Or passes if at least one validator passes. It is an alias for Any.

func Pattern

func Pattern(regex string, msg string) Validator

Pattern enforces a regex pattern match.

func Range

func Range(min, max float64, msg string) Validator

Range enforces a numeric value within min and max (inclusive).

func Required

func Required(msg string) Validator

Required ensures a value is present.

func URL

func URL(msg string) Validator

URL validates a basic URL format.

func UUID

func UUID() Validator

UUID validates a standard UUID string.

func When

func When(cond func() bool, v Validator) Validator

When conditionally applies a validator.

type Values

type Values map[string]any

Values is a map of form field values.

Jump to

Keyboard shortcuts

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