Form
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() // trueValidating 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) *FormGenerates 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) errorCopies datas from the form to a struct
End
func (f *Form) End() *FormConfigures its children deeply This function must be called after adding all
fields
GetField
func (f *Form) GetField(name string) *FieldReturns a child using its name
GetOption
func (f *Form) GetOption(name string) *OptionReturns an option using its name
HandleRequest
func (f *Form) HandleRequest(req *http.Request)Processes a request
HasField
func (f *Form) HasField(name string) boolChecks if the form contains a child using its name
HasOption
func (f *Form) HasOption(name string) boolChecks if the form contains an option using its name
IsSubmitted
func (f *Form) IsSubmitted() boolChecks if the form is submitted
IsValid
func (f *Form) IsValid() boolChecks the a form is valid
Mount
func (f *Form) Mount(data any) errorCopies datas from a struct to the form
ResetErrors
func (f *Form) ResetErrors() *FormResets the form errors
WithAction
func (f *Form) WithAction(v string) *FormSets the action of the form (eg: “/”)
WithMethod
func (f *Form) WithMethod(v string) *FormSets the method of the format (http.MethodPost, http.MethodGet, …)
WithName
func (f *Form) WithName(v string) *FormSets the name of the form (used to compute name of fields)
WithOptions
func (f *Form) WithOptions(options ...*Option) *FormAppends options to the form
Options
| Name | Type | Description |
|---|---|---|
attr |
map[string]string |
List of extra attributes |
help |
string |
Helper |