input

package
v0.0.20 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 2 Imported by: 0

README

Input Types

This package contains all input implementations for tinywasm/form. Each input implements ValidateField(value string) error and Clone(parentID, name string) Input. All inputs use only tinywasm/fmt — no errors or strconv from the standard library.

Available Inputs

Type HTML type Aliases Validation rules
Text text name, fullname, username Letters, Numbers, . , ( ), Min: 2, Max: 100
Email email mail, correo Letters, Numbers, @ . _ -, Min: 5, Max: 100
Password password pass, clave, pwd Any char, Min: 5, Max: 50
Number number num, amount, price, age Digits only (0-9), Min: 1, Max: 20 chars
Hour time hour HH:MM format, digits + :, validates 24 not valid
Date date fecha YYYY-MM-DD format, leap year + month/day range check
IP text ip, address IPv4 or IPv6 format; 0.0.0.0 rejected
Rut text rut, run, dni Chilean RUT XXXXXXX-D, verifies check digit
Phone tel phone, mobile, cell Digits, + ( ) -, Min: 7, Max: 15
Filepath text path, dir, file Letters, digits, .\/- _, no whitespace, Min: 1
Textarea textarea description, details, comments Wide char set incl. \n, Min: 5, Max: 2000
Checkbox checkbox check, boolean, bool true, false, on, 1, 0 or empty
Datalist text list, options Value must match one of the registered Options.Key
Select select select Value must match one of the registered Options.Key
Radio radio Value must match one of the registered Options.Key
Gender radio gender, sex m/f pre-wired options
Address text address, addr Letters, Numbers, . , - # /, Min: 5, Max: 200

No Standard Library

Rule: All input files must import only github.com/tinywasm/fmt. No errors, strconv, or strings.

Use the tinywasm/fmt equivalents:

// Instead of strconv.Atoi:
val, err := fmt.Convert("42").Int()

// Instead of errors.New:
return fmt.Err("Field", "Invalid")

// Instead of strings.ToLower:
lower := fmt.Convert(s).ToLower().String()

// Instead of strings.Contains:
found := fmt.Contains(haystack, needle)

Creating a Custom Input (embedding Base)

All inputs share the same pattern: embed Base, add a Permitted struct for rules, implement the Input interface.

package input

import "github.com/tinywasm/fmt"

// myInput is a custom input that only allows lowercase hex characters.
type myInput struct {
    Base
    Permitted Permitted
}

// MyInput creates a new instance ready for use.
func MyInput(parentID, name string) Input {
    m := &myInput{
        Permitted: Permitted{
            Letters:    true,
            Numbers:    true,
            Characters: []rune{},
            Minimum:    1,
            Maximum:    40,
        },
    }
    // Args: parentID, fieldName, htmlType, ...aliases
    m.Base.InitBase(parentID, name, "text", "myhex", "hex")
    m.Base.SetPlaceholder("e.g. 3f4a1b")
    m.Base.SetTitle("Lowercase hex only")
    return m
}

func (m *myInput) HTMLName() string { return m.Base.HTMLName() }

func (m *myInput) ValidateField(value string) error {
    // Custom rule: no uppercase letters
    for _, c := range value {
        if c >= 'A' && c <= 'F' {
            return fmt.Err("Character", "Invalid")
        }
    }
    return m.Permitted.Validate(value)
}

func (m *myInput) RenderHTML() string  { return m.Base.RenderInput() }

func (m *myInput) Clone(parentID, name string) Input {
    return MyInput(parentID, name)
}
Base Available Methods
Method Purpose
InitBase(parentID, name, htmlName, aliases...) Required — sets ID, name, html type and aliases
SetPlaceholder(string) HTML placeholder text
SetTitle(string) HTML title (tooltip)
SetOptions(...fmt.KeyValue) Options for select/radio/datalist
AddAttribute(key, value string) Custom extra HTML attributes
SetSkipValidation(bool) Skip validation entirely
RenderInput() Generates <input>, <textarea>, or <select> tag

Composition Pattern (wrapping another input)

Reuse existing inputs to create semantic wrappers:

func Gender(parentID, name string) Input {
    g := &gender{}
    g.Base.InitBase(parentID, name, "radio", "gender", "sex")
    g.Base.SetOptions(
        fmt.KeyValue{Key: "m", Value: "Male"},
        fmt.KeyValue{Key: "f", Value: "Female"},
    )
    return g
}

Matching Logic

The form engine matches struct fields to inputs in this order:

  1. LowerCase(FieldName) vs htmlName or aliases
  2. LowerCase(StructName.FieldName) vs aliases

Registering Custom Inputs

Register your own input type to make it available to form.New:

form.RegisterInput(MyCustomInput("", ""))

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Base

type Base struct {
	Values         []string       // Multiple values support (for select/checkbox/etc)
	Options        []fmt.KeyValue // Multiple options for select/checkbox/etc
	Placeholder    string
	Title          string
	Required       bool // HTML required attribute
	Disabled       bool // HTML disabled attribute
	Readonly       bool // HTML readonly attribute
	SkipValidation bool // Whether to skip validation for this input
	Attributes     []fmt.KeyValue
	// contains filtered or unexported fields
}

Base contains common logic and fields (State) for all inputs. It is intended to be embedded in concrete input structs.

func (*Base) AddAttribute

func (b *Base) AddAttribute(key, value string)

AddAttribute adds a custom attribute to the input.

func (*Base) Children added in v0.0.12

func (b *Base) Children() []dom.Component

Children returns empty slice (inputs are leaf nodes).

func (*Base) FieldName

func (b *Base) FieldName() string

FieldName returns the struct field name (without parent prefix).

func (*Base) GetID added in v0.0.12

func (b *Base) GetID() string

GetID returns the component's unique identifier.

func (*Base) GetOptions

func (b *Base) GetOptions() []fmt.KeyValue

GetOptions returns all options.

func (*Base) GetPlaceholder

func (b *Base) GetPlaceholder() string

GetPlaceholder returns the input placeholder.

func (*Base) GetSelectedValue

func (b *Base) GetSelectedValue() string

GetSelectedValue returns the first value in Values, or empty if none.

func (*Base) GetSkipValidation

func (b *Base) GetSkipValidation() bool

GetSkipValidation returns whether to skip validation.

func (*Base) GetTitle

func (b *Base) GetTitle() string

GetTitle returns the input title.

func (*Base) GetValue

func (b *Base) GetValue() string

GetValue returns the first value (for simple inputs).

func (*Base) GetValues

func (b *Base) GetValues() []string

GetValues returns all input values.

func (*Base) HTMLName

func (b *Base) HTMLName() string

HTMLName returns the HTML input type.

func (*Base) HandlerName added in v0.0.4

func (b *Base) HandlerName() string

HandlerName returns the component's unique identifier. Deprecated: use GetID instead.

func (*Base) InitBase

func (b *Base) InitBase(parentID, name, htmlName string, aliases ...string)

InitBase initializes the base fields and constructs the unique ID.

func (*Base) Matches

func (b *Base) Matches(fieldName string) bool

Matches checks if the given field name matches this input's htmlName, name or aliases.

func (*Base) RenderHTML added in v0.0.12

func (b *Base) RenderHTML() string

RenderHTML renders the input to HTML.

func (*Base) RenderInput

func (b *Base) RenderInput() string

RenderInput generates the standard HTML tag for the input.

func (*Base) SetAliases

func (b *Base) SetAliases(aliases ...string)

SetAliases sets the field name aliases for matching.

func (*Base) SetID added in v0.0.12

func (b *Base) SetID(id string)

SetID sets the component's unique identifier.

func (*Base) SetOptions

func (b *Base) SetOptions(opts ...fmt.KeyValue)

SetOptions sets multiple options (for select/checkbox/etc).

func (*Base) SetPlaceholder

func (b *Base) SetPlaceholder(ph string)

SetPlaceholder sets the input placeholder.

func (*Base) SetSkipValidation

func (b *Base) SetSkipValidation(skip bool)

SetSkipValidation sets whether to skip validation for this input.

func (*Base) SetTitle

func (b *Base) SetTitle(title string)

SetTitle sets the input title (tooltip).

func (*Base) SetValues

func (b *Base) SetValues(v ...string)

SetValues sets the input values.

type Input

type Input interface {
	dom.Component // Includes GetID(), SetID(), RenderHTML(), Children()

	HTMLName() string                  // Standard HTML5 type (e.g., "text", "email")
	FieldName() string                 // Struct field name (without parent prefix)
	ValidateField(value string) error  // Self-contained validation logic
	Clone(parentID, name string) Input // Creates a new instance with given parentID and name
}

Input interface defines the behavior for all form input types. It embeds dom.Component to ensure compatibility with the tinywasm/dom ecosystem.

func Address

func Address(parentID, name string) Input

Address creates a new Address input instance. It is a semantic wrapper around Text.

func Checkbox added in v0.0.19

func Checkbox(parentID, name string) Input

Checkbox creates a new checkbox input instance.

func Datalist added in v0.0.19

func Datalist(parentID, name string) Input

Datalist creates a new datalist input instance.

func Date added in v0.0.19

func Date(parentID, name string) Input

Date creates a new date input instance.

func Email

func Email(parentID, name string) Input

Email creates a new Email input instance.

func Filepath added in v0.0.19

func Filepath(parentID, name string) Input

Filepath creates a new filepath input instance.

func Gender

func Gender(parentID, name string) Input

Gender creates a new Gender input instance with default Male/Female options. It is a semantic wrapper around Radio.

func Hour added in v0.0.19

func Hour(parentID, name string) Input

Hour creates a new time input instance.

func IP added in v0.0.19

func IP(parentID, name string) Input

IP creates a new IP input instance.

func Number added in v0.0.19

func Number(parentID, name string) Input

Number creates a new number input instance.

func Password

func Password(parentID, name string) Input

Password creates a new Password input instance.

func Phone added in v0.0.19

func Phone(parentID, name string) Input

Phone creates a new phone input instance.

func Radio

func Radio(parentID, name string) Input

Radio creates a new Radio input instance.

func Rut added in v0.0.19

func Rut(parentID, name string) Input

Rut creates a new RUT input instance.

func Select

func Select(parentID, name string) Input

Select creates a new Select input instance.

func Text

func Text(parentID, name string) Input

Text creates a new Text input instance.

func Textarea added in v0.0.19

func Textarea(parentID, name string) Input

Textarea creates a new textarea input instance.

type Permitted

type Permitted struct {
	Letters         bool
	Tilde           bool
	Numbers         bool
	BreakLine       bool     // line breaks allowed
	WhiteSpaces     bool     // white spaces allowed
	Tabulation      bool     // tabulation allowed
	TextNotAllowed  []string // text not allowed eg: "hola" not allowed
	Characters      []rune   // other special characters eg: '\','/','@'
	Minimum         int      // min characters eg 2 "lo" ok default 0 no defined
	Maximum         int      // max characters eg 1 "l" ok default 0 no defined
	ExtraValidation func(string) error
	StartWith       *Permitted // characters allowed at the beginning
}

func (Permitted) MinMaxAllowedChars

func (p Permitted) MinMaxAllowedChars() (min, max int)

func (Permitted) Validate

func (h Permitted) Validate(text string) (err error)

Jump to

Keyboard shortcuts

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