Form

Example

Prerequisites

import (
	"gitnet.fr/deblan/go-form/form"
	"gitnet.fr/deblan/go-form/validation"
)

type Person struct {
    Name string
    Age  int
}

Creating a form

myForm := form.NewForm(
    form.NewFieldText("Name").
        WithConstraints(
            validation.NewNotBlank(),
        ),
    form.NewFieldNumber("Age").
        WithConstraints(
            validation.NewNotBlank(),
            validation.NewRange().WithMin(18),
        ),
).End()

Validating a struct

data := Person{}

myForm.Mount(data)
myForm.IsValid() // false

data = Person{
    Name: "Alice",
    Age:  42,
}

myForm.Mount(data)
myForm.IsValid() // true

Validating a request

import (
    "net/http"
)

myForm.WithMethod(http.MethodPost)

// req *http.Request
if req.Method == myForm.Method {
    myForm.HandleRequest(req)

    if myForm.IsSubmitted() && myForm.IsValid() {
        myForm.Bind(&data)
    }
}

Struct

type Form struct {
	Fields       []*Field
	GlobalFields []*Field
	Errors       []validation.Error
	Method       string
	Action       string
	Name         string
	Options      []*Option
	RequestData  *url.Values
}

Methods

NewForm

func NewForm(fields ...*Field) *Form

Generates a new form with default properties

Add

func (f *Form) Add(fields ...*Field)

Appends children

AddGlobalField

func (f *Form) AddGlobalField(field *Field)

Configures its children deeply

Bind

func (f *Form) Bind(data any) error

Copies datas from the form to a struct

End

func (f *Form) End() *Form

Configures its children deeply This function must be called after adding all

fields

GetField

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

Returns a child using its name

GetOption

func (f *Form) GetOption(name string) *Option

Returns an option using its name

HandleRequest

func (f *Form) HandleRequest(req *http.Request)

Processes a request

HasField

func (f *Form) HasField(name string) bool

Checks if the form contains a child using its name

HasOption

func (f *Form) HasOption(name string) bool

Checks if the form contains an option using its name

IsSubmitted

func (f *Form) IsSubmitted() bool

Checks if the form is submitted

IsValid

func (f *Form) IsValid() bool

Checks the a form is valid

Mount

func (f *Form) Mount(data any) error

Copies datas from a struct to the form

ResetErrors

func (f *Form) ResetErrors() *Form

Resets the form errors

WithAction

func (f *Form) WithAction(v string) *Form

Sets the action of the form (eg: “/”)

WithMethod

func (f *Form) WithMethod(v string) *Form

Sets the method of the format (http.MethodPost, http.MethodGet, …)

WithName

func (f *Form) WithName(v string) *Form

Sets the name of the form (used to compute name of fields)

WithOptions

func (f *Form) WithOptions(options ...*Option) *Form

Appends options to the form

Options

Name Type Description
attr map[string]string List of extra attributes
help string Helper