form

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package form provides type-safe form handling with validation for Vango applications.

Deprecated: The v1 Developer Guide expects form usage via `setup.Form` and `vango` re-exports. This package is retained for legacy/internal use only.

Overview

The form package provides a generic Form[T] type that binds to Go structs, offering declarative validation through struct tags and built-in validators.

Basic Usage

type ContactForm struct {
    Name    string `form:"name" validate:"required,min=2,max=100"`
    Email   string `form:"email" validate:"required,email"`
    Message string `form:"message" validate:"required,max=1000"`
}

func ContactPage(p vango.NoProps) vango.Component {
    return vango.Setup(p, func(s vango.SetupCtx[vango.NoProps]) vango.RenderFn {
        form := setup.Form(&s, ContactForm{})

        submit := func() {
            if !form.Validate() {
                return // Errors displayed automatically
            }
            data := form.Values()
            sendEmail(data.Name, data.Email, data.Message)
            form.Reset()
        }

        return func() *vango.VNode {
            return Form(OnSubmit(submit),
                form.Field("Name", Input(Type("text"))),
                form.Field("Email", Input(Type("email"))),
                form.Field("Message", Textarea()),
                Button(Type("submit"), Text("Send")),
            )
        }
    })
}

Validation

The package includes built-in validators for common patterns:

  • Required: Non-empty value
  • MinLength/MaxLength: String length constraints
  • Email: Valid email format
  • Pattern: Regular expression matching
  • Min/Max: Numeric range constraints
  • Custom: User-defined validation logic

Form Arrays

For forms with dynamic arrays of nested objects, use the Array method:

form.Array("Items", func(item FormArrayItem, i int) *vango.VNode {
    return Div(
        item.Field("Name", Input(Type("text"))),
        Button(OnClick(item.Remove), Text("Remove")),
    )
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeFormValues

func DecodeFormValues(values map[string][]string, dst any) error

DecodeFormValues parses form values into the provided struct pointer. It returns ParseErrors when any fields fail to parse.

Types

type AsyncValidator

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

AsyncValidator wraps an async validation function. The function returns (error, isComplete).

func Async

func Async(fn func(value any) (error, bool)) *AsyncValidator

Async creates an async validator for server-side checks.

func (*AsyncValidator) IsComplete

func (a *AsyncValidator) IsComplete() bool

IsComplete returns true if the async validation has completed.

func (*AsyncValidator) IsLoading

func (a *AsyncValidator) IsLoading() bool

IsLoading returns true if the async validation is in progress.

func (*AsyncValidator) Validate

func (a *AsyncValidator) Validate(value any) error

type EqualToField

type EqualToField struct {
	Field   string
	Message string
	// contains filtered or unexported fields
}

EqualToField creates a validator that checks if the value equals another field. Note: This validator needs form context, so it's typically added via Form.AddValidators.

func EqualTo

func EqualTo(field string, msg string) *EqualToField

EqualTo returns a validator factory function. The actual comparison happens when the form is validated.

func (*EqualToField) SetForm

func (e *EqualToField) SetForm(form interface{ Get(string) any })

SetForm sets the form context for comparison validators.

func (*EqualToField) Validate

func (e *EqualToField) Validate(value any) error

type Form

type Form[T any] struct {
	// contains filtered or unexported fields
}

Form is a type-safe form handler with validation support. It provides reactive form state management, field-level validation, and automatic binding to Go structs via struct tags.

func SetupForm

func SetupForm[P any, T any](s *vango.SetupCtx[P], initial T) *Form[T]

SetupForm creates a new Form bound to the given struct type during Setup. Signals are allocated during setup using the setup helpers.

func (*Form[T]) AddValidators

func (f *Form[T]) AddValidators(field string, validators ...Validator)

AddValidators adds validators for a field. This allows adding validators programmatically instead of via struct tags.

func (*Form[T]) AppendTo

func (f *Form[T]) AppendTo(field string, value any)

AppendTo adds a new item to an array field.

func (*Form[T]) Array

func (f *Form[T]) Array(field string, fn func(item FormArrayItem, index int) *vdom.VNode) *vdom.VNode

Array renders items in a form array using the provided render function. Each item is passed a FormArrayItem for accessing its fields.

func (*Form[T]) ArrayKeyed

func (f *Form[T]) ArrayKeyed(field string, keyFn func(item any) any, fn func(item FormArrayItem, index int) *vdom.VNode) *vdom.VNode

ArrayKeyed renders items in a form array using RangeKeyed for stable identity. The key function must return a stable key for each item.

func (*Form[T]) ArrayLen

func (f *Form[T]) ArrayLen(field string) int

ArrayLen returns the length of an array field.

func (*Form[T]) ClearErrors

func (f *Form[T]) ClearErrors()

ClearErrors removes all validation errors.

func (*Form[T]) ClearParseErrors

func (f *Form[T]) ClearParseErrors()

ClearParseErrors removes all parse errors.

func (*Form[T]) Errors

func (f *Form[T]) Errors() map[string][]string

Errors returns all validation errors keyed by field name.

func (*Form[T]) Field

func (f *Form[T]) Field(name string, input *vdom.VNode, validators ...Validator) *vdom.VNode

Field wraps an input element with value binding and error display. It automatically binds the input value to the form field and shows errors.

The input's oninput and onblur handlers are chained (not replaced) if they exist. Handler signature is func(string) for the input value.

func (*Form[T]) FieldDirty

func (f *Form[T]) FieldDirty(field string) bool

FieldDirty returns true if the specific field has been modified.

func (*Form[T]) FieldErrors

func (f *Form[T]) FieldErrors(field string) []string

FieldErrors returns validation errors for a specific field.

func (*Form[T]) FieldParseError

func (f *Form[T]) FieldParseError(field string) string

FieldParseError returns the parse error for a specific field.

func (*Form[T]) Get

func (f *Form[T]) Get(field string) any

Get returns the value of a single field by name. Supports dot notation for nested fields (e.g., "address.city").

func (*Form[T]) GetBool

func (f *Form[T]) GetBool(field string) bool

GetBool returns a field value as a bool.

func (*Form[T]) GetInt

func (f *Form[T]) GetInt(field string) int

GetInt returns a field value as an int.

func (*Form[T]) GetString

func (f *Form[T]) GetString(field string) string

GetString returns a field value as a string.

func (*Form[T]) HasError

func (f *Form[T]) HasError(field string) bool

HasError returns true if the field has any validation errors.

func (*Form[T]) InsertAt

func (f *Form[T]) InsertAt(field string, index int, value any)

InsertAt inserts an item into an array field at the given index.

func (*Form[T]) IsDirty

func (f *Form[T]) IsDirty() bool

IsDirty returns true if any field has been modified.

func (*Form[T]) IsSubmitting

func (f *Form[T]) IsSubmitting() bool

IsSubmitting returns true if the form is currently being submitted.

func (*Form[T]) IsTouched

func (f *Form[T]) IsTouched(field string) bool

IsTouched returns true if the field has been interacted with.

func (*Form[T]) IsValid

func (f *Form[T]) IsValid() bool

IsValid returns true if there are no validation errors.

func (*Form[T]) ParseErrors

func (f *Form[T]) ParseErrors() map[string]string

ParseErrors returns all parse errors keyed by field name.

func (*Form[T]) RemoveAt

func (f *Form[T]) RemoveAt(field string, index int)

RemoveAt removes an item from an array field at the given index.

func (*Form[T]) Reset

func (f *Form[T]) Reset()

Reset restores the form to its initial values and clears errors.

func (*Form[T]) Set

func (f *Form[T]) Set(field string, value any)

Set updates a single field value. Supports dot notation for nested fields.

func (*Form[T]) SetError

func (f *Form[T]) SetError(field string, msg string)

SetError manually sets an error message for a field.

func (*Form[T]) SetParseError

func (f *Form[T]) SetParseError(field string, msg string)

SetParseError manually sets a parse error message for a field.

func (*Form[T]) SetSubmitting

func (f *Form[T]) SetSubmitting(submitting bool)

SetSubmitting sets the submitting state.

func (*Form[T]) SetValues

func (f *Form[T]) SetValues(values T)

SetValues replaces all form values with the given struct.

func (*Form[T]) Validate

func (f *Form[T]) Validate() bool

Validate runs all validators and returns true if the form is valid. Validation errors are stored and can be accessed via Errors() or FieldErrors().

func (*Form[T]) ValidateField

func (f *Form[T]) ValidateField(field string) bool

ValidateField validates a single field and returns true if valid.

func (*Form[T]) Values

func (f *Form[T]) Values() T

Values returns a copy of the current form values as the typed struct.

type FormArrayItem

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

FormArrayItem represents an item in a form array. It provides field access scoped to the array element's path.

func (FormArrayItem) Field

func (i FormArrayItem) Field(name string, input *vdom.VNode, validators ...Validator) *vdom.VNode

Field wraps an input for an array item field. The path is automatically prefixed with the item's path.

func (FormArrayItem) Index

func (i FormArrayItem) Index() int

Index returns the zero-based index of this item in the array.

func (FormArrayItem) Path

func (i FormArrayItem) Path() string

Path returns the full path to this item (e.g., "Items.0").

func (FormArrayItem) Remove

func (i FormArrayItem) Remove() func()

Remove removes this item from the array. Returns a function suitable for use with OnClick.

type NotEqualToField

type NotEqualToField struct {
	Field   string
	Message string
	// contains filtered or unexported fields
}

NotEqualToField creates a validator that checks if the value differs from another field.

func NotEqualTo

func NotEqualTo(field string, msg string) *NotEqualToField

NotEqualTo returns a validator that ensures the value differs from another field.

func (*NotEqualToField) SetForm

func (e *NotEqualToField) SetForm(form interface{ Get(string) any })

func (*NotEqualToField) Validate

func (e *NotEqualToField) Validate(value any) error

type ParseErrors

type ParseErrors map[string]string

ParseErrors represents per-field parse errors.

func (ParseErrors) Error

func (p ParseErrors) Error() string

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a validation failure.

func (ValidationError) Error

func (e ValidationError) Error() string

type Validator

type Validator interface {
	// Validate checks if the value is valid.
	// Returns nil if valid, or an error with a message if invalid.
	Validate(value any) error
}

Validator is an interface for form field validation.

func Alpha

func Alpha(msg string) Validator

Alpha validates that the value contains only ASCII letters.

func AlphaNumeric

func AlphaNumeric(msg string) Validator

AlphaNumeric validates that the value contains only letters and digits.

func Between

func Between(min, max any, msg string) Validator

Between validates that a numeric value is between min and max (inclusive).

func Custom

func Custom(fn func(value any) error) Validator

Custom creates a validator from a custom function.

func DateAfter

func DateAfter(t time.Time, msg string) Validator

DateAfter validates that a date/time is after the given time.

func DateBefore

func DateBefore(t time.Time, msg string) Validator

DateBefore validates that a date/time is before the given time.

func Email

func Email(msg string) Validator

Email validates that the value is a valid email address.

func Future

func Future(msg string) Validator

Future validates that a date/time is in the future.

func Max

func Max(n any, msg string) Validator

Max validates that a numeric value is <= n.

func MaxLength

func MaxLength(n int, msg string) Validator

MaxLength validates that a string has at most n characters.

func Min

func Min(n any, msg string) Validator

Min validates that a numeric value is >= n.

func MinLength

func MinLength(n int, msg string) Validator

MinLength validates that a string has at least n characters.

func NonNegative

func NonNegative(msg string) Validator

NonNegative validates that a numeric value is >= 0.

func Numeric

func Numeric(msg string) Validator

Numeric validates that the value contains only digits.

func Past

func Past(msg string) Validator

Past validates that a date/time is in the past.

func Pattern

func Pattern(pattern string, msg string) Validator

Pattern validates that a string matches the given regular expression.

func Phone

func Phone(msg string) Validator

Phone validates that the value looks like a phone number.

func Positive

func Positive(msg string) Validator

Positive validates that a numeric value is > 0.

func Required

func Required(msg string) Validator

Required validates that the value is non-empty.

func URL

func URL(msg string) Validator

URL validates that the value is a valid URL.

func UUID

func UUID(msg string) Validator

UUID validates that the value is a valid UUID.

type ValidatorFunc

type ValidatorFunc func(value any) error

ValidatorFunc is a function that implements Validator.

func (ValidatorFunc) Validate

func (f ValidatorFunc) Validate(value any) error

Jump to

Keyboard shortcuts

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