Awesome Go

go-form

CategoryForms
SubcategoryForms
Stars46

Render HTML forms from Go structs with struct tags, bind and validate submissions

About go-form

This large README is shown as a plain-text preview. Read the full README at the source

<p align="center">
    <a href="https://docs.gowebthings.com/go-form">
        <img src="./assets/go-form-logo.png" alt="go-form" height="70">
    </a>
</p>

# go-form

[![Go Reference](https://pkg.go.dev/badge/github.com/donseba/go-form/v2.svg)](https://pkg.go.dev/github.com/donseba/go-form/v2)
[![codecov](https://codecov.io/gh/donseba/go-form/graph/badge.svg)](https://codecov.io/gh/donseba/go-form)

[Documentation](https://docs.gowebthings.com/go-form) · Part of [go-webthings](https://gowebthings.com/components).

A Go library for rendering HTML forms from Go structs using struct tags and Go templates. Supports multiple template styles (Plain, Bootstrap 5, Tailwind CSS) and a wide range of HTML input types.

---

## Features

- Define forms as Go structs with struct tags for field type, label, placeholder, and more
- Supports many HTML input types: text, password, email, tel, number, date, color, range, datetime-local, time, week, month, hidden
- Checkbox, radio, dropdown, and textarea fields
- Grouping and nested struct support for form sections
- Built-in themes: Plain, Bootstrap 5, Tailwind CSS v3 and v4
- Integrates with `html/template` via a FuncMap, rendering a whole form or [field by field](#laying-out-fields-yourself)
- [Forms defined at runtime](#forms-defined-at-runtime) (`Schema`) render and validate like structs
- [File uploads](#file-uploads), [time zones](#time-zones), [trimming](#trimming-white-space), [strict mapping](#strict-mapping) and [read-only forms](#read-only-forms)
- [Binding](#binding-a-submission) a submission in one step, [limits](#limits-that-change-at-runtime) and [options](#options-known-at-render-time) that change at runtime for rendering and validation alike, and [showing a failed submission again](#showing-a-failed-submission-again) after a redirect
- [Text extraction](#extracting-texts) for translators, and [rendering from Go](#rendering-from-go)
- CSRF Protection, and a [honeypot](#spam-honeypot) against spam bots
- Messages in English and Dutch, in the localizer's language ([message catalogues](#message-catalogues))
- **SortedSelect** and **SortedMultiSelect** for type-safe, mapped dropdowns and multi-selects, sorted by key or label or in [your own order](#ordered-selects-and-placeholders)

---

## Installation

```sh
go get github.com/donseba/go-form/v2
```

---

## Quick Start

```go
package main

import (
	"html/template"
	"log"
	"os"

	"github.com/donseba/go-form/v2"
)

type Contact struct {
	Name  string `form:"input,text" label:"Name" required:"true"`
	Email string `form:"input,email" label:"Email" required:"true"`
}

func main() {
	renderer := form.NewForm()
	renderer.SetTheme("plain")

	page := template.Must(template.New("contact").Funcs(renderer.FuncMap()).Parse(
		`{{ form_render .Form .Errors }}`,
	))
	model := form.WithInfo(Contact{}, form.Info{
		Target: "/contacts", Method: "post", SubmitText: "Save contact",
	})
	if err := page.Execute(os.Stdout, map[string]any{
		"Form": model, "Errors": form.FieldErrors(nil),
	}); err != nil {
		log.Fatal(err)
	}
}
```

---

The example prints form HTML. In an HTTP handler, use `WithRequestInfo` and wrap the handler with the same renderer's `CSRFMiddleware()` to supply and validate the CSRF token. Use `form.MapForm(r, &input)` to map a submission and `renderer.ValidateForm(&input)` to collect field errors, or `renderer.Bind` for both in one step (see [Binding a Submission](#binding-a-submission)). Form metadata stays outside your application struct.

## Supported Templates

Select a theme with `renderer.SetTheme(name)` before serving requests.

| Theme name | Description |
|------------|-------------|
| `plain` | Plain HTML with minimal inline styles |
| `bootstrap` | Bootstrap 5 classes (default) |
| `tailwind` | Tailwind CSS v3 classes |
| `tailwindv4` | Tailwind CSS v4 classes |

Class-based themes require your application to load the corresponding stylesheet.

### Your Own Theme

`templates.RegisterClassTheme` registers a theme with your CSS classes and go-form's markup. Registering the same name and classes again returns the same theme, so it can run where the renderer is created:

```go
_, err := templates.RegisterClassTheme("site", templates.ThemeClasses{
    Wrapper: templates.StyleOption{Class: "field"},
    Label:   templates.StyleOption{Class: "field-label"},
    Input:   templates.StyleOption{Class: "control"},
    Error:   templates.StyleOption{Class: "field-error"},
})
if err != nil {
    return err
}

renderer.SetTheme("site")
```

A theme of your own hides text for screen readers only, such as the `(required)` of a required field, with the class `sr-only` unless `VisuallyHidden` names another class, so its CSS needs a rule for that class.

A group of radio buttons, and a multicheckbox, renders as a `<fieldset>` with the field's label as its `<legend>` (`fieldset.gohtml` and `legend.gohtml`), so the question names the group for screen readers: the fieldset gets the classes of `Wrapper` and `Fieldset`, the legend those of `Label` and `Legend`. Use `Fieldset` and `Legend` for what only the group needs, such as a reset of the browser's fieldset border and padding (the plain theme has one inline).

To change the markup, load a complete template set of your own into a theme with `LoadTemplatesFS` (or `LoadTemplates` from disk), such as a copy of go-form's templates in `templates/gohtml` (`input.gohtml`, `select.gohtml`, `wrapper.gohtml`, `fieldset.gohtml`, `form-buttons.gohtml`, …) with your changes. Your templates can use the same functions as go-form's, such as `themeClass`, `form_print`, `form_described_by` and `form_class`, which joins the classes that are not empty, so an attribute without classes can be left out: `{{with form_class (themeClass "input") .Field.Class}}class="{{.}}"{{end}}`. Register themes and load their templates before serving requests, under a name of your own.

The opening form tag comes from `form-open.gohtml`, which `form_open` renders and `form_render` too, through `form.gohtml`. A `form-open.gohtml` of your own, or a `form.gohtml` that writes the tag itself, renders the form's attributes besides `action` and `method` with four functions, as go-form's `form-open.gohtml` does:

- `form_open_class` and `form_open_style`: the classes and inline style of `Info.Attributes` and of `form_open`, besides the theme's (`themeClass "form"`, `themeStyle "form"`); join them with `form_class` and `form_style`;
- `form_attributes .Field.Attributes`: the other attributes of `Info.Attributes`, such as `enctype`;
- `form_open_attributes`: the other attributes the template gave `form_open` (see [Attributes in the Template](#attributes-in-the-template)).

A template that leaves one out drops those attributes.

---

## Supported Input Fields & Options

| Field Type / Tag Example         | Description         | Options (Struct Tags)                                  |
|----------------------------------|---------------------|-------------------------------------------------------|
| `form:"input,text"`             | Text input          | `label`, `placeholder`, `required`, `minLength`, `maxLength`, `pattern` |
| `form:"input,password"`         | Password input      | `label`, `placeholder`, `required`, `autocomplete`     |
| `form:"input,email"`            | Email input         | `label`, `placeholder`, `required`, `multiple`         |
| `form:"input,number"`           | Number input        | `label`, `placeholder`, `required`, `min`, `max`, `step`|
| `form:"input,date"`             | Date input          | `label`, `placeholder`, `required`                     |
| `form:"input,datetime-local"`   | DateTime input      | `label`, `placeholder`, `required`                     |
| `form:"input,time"`             | Time input          | `label`, `placeholder`, `required`                     |
| `form:"input,week"`             | Week input          | `label`, `placeholder`, `required`                     |
| `form:"input,month"`            | Month input         | `label`, `placeholder`, `required`                     |
| `form:"input,color"`            | Color input         | `label`, `placeholder`, `required`                     |
| `form:"input,range"`            | Range input         | `label`, `min`, `max`, `step`                          |
| `form:"input,hidden"`           | Hidden input        | none; it sends the field's value                       |
| `form:"input,file"`             | File input          | `label`, `required`, `accept`, `multiple`, `maxSize` (see [File uploads](#file-uploads)) |
| `form:"input,search"`           | Search input        | `label`, `placeholder`                                 |
| `form:"input,url"`              | URL input           | `label`, `placeholder`                                 |
| `form:"input,tel"`              | Telephone input     | `label`, `placeholder`                                 |
| `form:"input,image"`            | Image input         | `label` (there are no `src` and `alt` tags)            |
| `form:"textarea"`               | Textarea            | `label`, `placeholder`, `required`, `rows`, `cols`, `minLength`, `maxLength` |
| `form:"checkbox"`               | Checkbox            | `label`, `required`                                    |
| `form:"radios"`                 | Radio group         | `label`, `values` (e.g. `a:A;b:B`), `required`         |
| `form:"dropdown"`               | Dropdown/select     | `label`, `values` (e.g. `a:A;b:B`), `required`, `placeholder` (an empty first option) |
| `form:"multicheckbox"`          | Multi-checkbox group| `label`, `values` (e.g. `a:A;b:B`), `required`, `minItems`, `maxItems` (slice fields and `SortedMultiSelect`) |

A field with a `values` tag may be a string, any integer kind (`values:"60:1 minute;300:5 minutes"` on an `int`), a pointer to one, or for a multi-checkbox a slice of them (`[]string`, `[]int`). Options only known when the form renders, such as the answers of a poll, are given with [`RenderModel.Options`](#options-known-at-render-time).

A struct radio group is a struct field with `form:"radios"` whose bool fields carry the struct's `name`: it renders a radio button per bool field, with the field's `label`, and `MapForm` ticks the chosen field and clears the others. `form:"radios,radio_group"`, with a `legend`, declares the same group explicitly.

```go
type PlanChoice struct {
    Monthly bool `name:"plan" label:"Monthly"`
    Yearly  bool `name:"plan" label:"Yearly"`
}

type SignupInput struct {
    Plan PlanChoice `form:"radios" name:"plan" label:"Plan"`
}
```

Number fields may be pointers, such as `*float64`, to tell "not filled in" (`nil`) from `0`. An optional coordinate:

```go
Latitude *float64 `form:"input,number" label:"Latitude" step:"any" min:"-90" max:"90"`
```

Other supported tags:
- `legend` — For grouping/nested structs (section title)
- `description` — Field description/help text
- `maxLength` — Maximum length for textarea or string input
- `class` — Custom CSS class for the field
- `data` — Custom data attributes: `data:"custom=value,foo=bar"` renders `data-custom="value" data-foo="bar"`
- `translate` — Translate option labels: `translate:"true"` for Enumerator, Mapper and SortedMapper fields (such as `SortedSelect`), `translate:"false"` to keep labels from a `values` tag as written (see [Translating Option Labels](#translating-option-labels))
- `disabled:"true"` — Renders the control disabled: inputs (also hidden and range inputs), textareas, selects, checkboxes, radios and multicheckboxes. Browsers do not submit disabled controls, so `MapForm` leaves such a field as it was, except that a disabled checkbox becomes `false` and, on a POST, a disabled multicheckbox empty. Use `readonly:"true"` for a text field whose value must be sent
- `readonly:"true"` — Renders a text-like input or textarea read-only
- `autocomplete` — The `autocomplete` attribute, such as `autocomplete:"email"`, `autocomplete:"current-password"` or `autocomplete:"new-password"`
- `accept`, `multiple` — For file inputs (`accept:"image/*,.pdf"`); `multiple` also for email inputs
- `minLength`, `maxLength` — Checked on the server and rendered as `minlength` and `maxlength`
- `pattern` — Checked on the server; rendered as the `pattern` attribute only when browsers check it the same way: a pattern anchored with `^` and `$`, without Go-only syntax such as `(?i)` and without a top-level `|`. Other patterns are only checked on the server.
- `placeholder` on a dropdown — Renders an empty first option with that label, such as `placeholder:"—"`
- `line:"true"` — The value must be one line without control characters (see [Built-in Validation](#built-in-validation))
- `wallclock:"true"` — A `datetime-local` field read and shown without a time zone (see [Time Zones](#time-zones))

A field with errors renders its control with `aria-invalid="true"` and an `aria-describedby` that names its description and its error messages (`<id>_description`, `<id>_error_0`, …), so screen readers read them with the control.

---

## Laying Out Fields Yourself

`form_render` renders the whole form. To lay out the fields yourself, such as two fields side by side or a field between your own markup, render them one at a time:

```gohtml
{{ form_open .Form }}
  <div class="row">
    <div class="col">{{ form_field .Form "FirstName" .Errors }}</div>
    <div class="col">{{ form_field .Form "LastName" .Errors }}</div>
  </div>
  {{ form_field .Form "address.city" .Errors }}
  <input name="custom" value="…">
  {{ range form_errors .Errors "custom" }}<p class="error">{{ . }}</p>{{ end }}
  {{ form_buttons .Form }}
{{ form_close }}
```

| Function | Renders |
|----------|---------|
| `form_field model name errors` | One field with its label, description and errors, by the name it renders with (the `name` tag, nested as `address.city`). A group renders with all its fields. |
| `form_errors errors name` | The messages for one field, as `[]string` (also `errors.Messages(name)` in Go). |
| `form_open model [attributes…]` | The opening `<form>` tag with its attributes, and the hidden fields: the CSRF token, the honeypot and `Info.Hidden`. Attributes of the template's own follow the model (see [Attributes in the Template](#attributes-in-the-template)). |
| `form_hidden model` | The hidden fields of `form_open` alone, for a `<form>` tag you write yourself. |
| `form_buttons model` | The cancel link and submit button (no submit button in a read-only form). |
| `form_close` | The closing `</form>` tag. |
| `form_honeypot name` | The spam trap input for a form whose markup you write yourself (see [Spam Honeypot](#spam-honeypot)). |
| `form_has_fields model` | Whether the model has a field to render (`form.HasFields` in Go). |

`form_field_localized`, `form_open_localized`, `form_hidden_localized` and `form_buttons_localized` take a localizer first, like `form_render_localized`. Fields render with the selected theme, so they look the same as in `form_render`. The submit button shows `Info.SubmitText`, or `form.DefaultSubmitText` (`Submit`) when it is empty.

A name the model does not have fails the template, and the error lists the fields the model has, each by the name `form_field` takes, with a group's fields after the group. A typing mistake then shows the right name. For a model with `name`, `email` and an `address` group with `city`:

```text
form: no field "nmae" (fields: name, email, address, address.city)
```

### Attributes in the Template

`form_open` takes attributes of the template's own after the model: name/value pairs and `template.HTMLAttr` values, such as the attributes another library renders for a form that submits with HTMX. go-form does not need to know that library:

```gohtml
{{ form_open .Form "class" "booking" (submitAttrs runtime .Action "target" "#booking" "swap" "outerHTML") }}
  {{ form_field .Form "name" .Errors }}
  <button type="submit">Book</button>
{{ form_close }}
```

```html
<form action="/book" method="post" class="site-form booking" hx-post="/book" hx-target="#booking" hx-swap="outerHTML">
<input type="text" name="website" … aria-hidden="true">
<input type="hidden" name="back" value="/workshop#booking">
```

- `class` adds to the theme's class and to `Info.Attributes["class"]`, in one `class` attribute; a class that is already there is not repeated. `style` adds to the theme's and `Info.Attributes["style"]` the same way.
- `action`, `method` and `enctype` come from the form metadata (`Info.Target`, `Info.Method`, `Info.Attributes["enctype"]` or a file input). Giving them in the template is an error, rather than a second attribute the browser ignores.
- Any other attribute replaces the one of the same name in `Info.Attributes`; given twice, the last one counts.
- The values of pairs are escaped. A pair cannot set an event handler (`on…`); that takes a trusted `template.HTMLAttr`. A `nil` value renders the name alone, such as `"novalidate" nil`; a `nil` attribute is skipped, so an optional one can be left out.

From Go, `Open(loc, model, attributes...)` renders the same. A template that has to write the `<form>` tag itself renders the hidden fields with `{{ form_hidden .Form }}` (`Hidden(loc, model)` in Go).

### Hidden Fields

`Info.Hidden` adds hidden inputs to the form, such as the page to return to. `form_open` and `form_render` render them after the CSRF token and the honeypot, one input per value, in name order:

```go
model := form.WithInfo(input, form.Info{
    Target: "/comments", Method: "post", Honeypot: "website",
    Hidden: url.Values{"back": {r.URL.Path + "#comments"}},
})
```

### Several Forms on One Page

Fields render with their name as their id (`id="email"`), which labels, descriptions and errors refer to. Two forms on one page with a field of the same name, such as a newsletter form and a comment form, so collide. `Info.IDPrefix` puts a prefix and a dash before every id of a form, and before the ids that `for`, `aria-labelledby` and `aria-describedby` refer to; names stay as they are:

```go
newsletter := form.WithInfo(SubscribeInput{}, form.Info{Target: "/subscribe", Method: "post", IDPrefix: "newsletter"})
// <label for="newsletter-email" id="newsletter-email_label"> <input id="newsletter-email" name="email" …>
```

Without a prefix the ids are the names, as before.

### Rendering from Go

The template functions are methods of `*form.Form` too, for applications that wrap them in template functions of their own, such as functions that take the localizer of the page from a context. A nil localizer renders as the functions without a localizer do (`form.DefaultLocalizer`, English).

| Method | Template function |
|--------|-------------------|
| `Render(loc, model, errs)` | `form_render_localized` |
| `Field(loc, model, name, errs)` | `form_field_localized` |
| `Open(loc, model, attributes...)` | `form_open_localized`, with or without attributes |
| `Hidden(loc, model)` | `form_hidden_localized` |
| `Buttons(loc, model)` | `form_buttons_localized` |
| `Close()` | `form_close` |
| `Honeypot(loc, name)` | `form_honeypot` |

```go
funcs := template.FuncMap{
    "form_field": func(ctx context.Context, model any, name string, errs form.FieldErrors) (template.HTML, error) {
        return renderer.Field(localizerFrom(ctx), model, name, errs)
    },
}
```

## Limits That Change at Runtime

Some limits are only known when the form renders, such as the places left at an event. `form.Overrides` replace struct tags of fields by the name they render with, for rendering and validation alike, so the browser and the server check the same limit. A model that implements `Overrider` gets them everywhere: when it renders, in `ValidateForm` and in `Bind`:

```go
type BookingInput struct {
    Adults int `form:"input,number" name:"adults" label:"Adults" min:"1" max:"50"`

    left int // the places left; unexported fields never render
}

func (in BookingInput) FormOverrides() form.Overrides {

Frequently Asked Questions

What is go-form?

go-form is a Forms library for the Go programming language. Render HTML forms from Go structs with struct tags, bind and validate submissions

How do I install go-form?

Install go-form with the Go module system using `go get donseba/go-form`. Check the repository for the current installation instructions.

What category does go-form belong to?

go-form is listed under Forms, specifically Forms.

← Back to Forms