Server-rendered apps with Go, templ and HTMX
Forms, validation and errors
Server-side validation, re-rendering a form with messages, how htmx 4 treats status codes, and redirect-after-post for clients without htmx.
- lesson
- 05 of 08
- read
- 16 min
The add form accepts an empty title and a javascript: URL. This lesson validates submissions on the server, sends the form back with the user’s input and a message per field when something is wrong, and picks status codes that work for htmx and for a plain browser. It ends with a place for failures that are not the user’s fault.
Validate on the server
package main
import (
"fmt"
"net/url"
"strings"
"unicode/utf8"
)
const (
maxTitleLen = 120
maxNoteLen = 280
)
// LinkForm holds what the user typed and what was wrong with it.
type LinkForm struct {
URL string
Title string
Note string
Errors map[string]string
}
// Validate normalizes the fields and reports whether they are acceptable.
// Problems are recorded in Errors, keyed by field name.
func (f *LinkForm) Validate() bool {
f.URL = strings.TrimSpace(f.URL)
f.Title = strings.TrimSpace(f.Title)
f.Note = strings.TrimSpace(f.Note)
f.Errors = map[string]string{}
u, err := url.Parse(f.URL)
switch {
case f.URL == "":
f.Errors["url"] = "Enter a URL."
case err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https"):
f.Errors["url"] = "Enter a full http or https URL."
}
switch {
case f.Title == "":
f.Errors["title"] = "Enter a title."
case utf8.RuneCountInString(f.Title) > maxTitleLen:
f.Errors["title"] = fmt.Sprintf("Use at most %d characters.", maxTitleLen)
}
if utf8.RuneCountInString(f.Note) > maxNoteLen {
f.Errors["note"] = fmt.Sprintf("Use at most %d characters.", maxNoteLen)
}
return len(f.Errors) == 0
}LinkForm holds the raw strings the user typed next to what was wrong with them. It is separate from Link on purpose: a form has to be able to hold values that would never be allowed into the store, so they can be shown back. Validate trims the fields, records problems by field name and reports whether there were any. Lengths are counted in characters with utf8.RuneCountInString, since len counts bytes.
The required and type="url" attributes in the markup stay. They give quick feedback, but they are not validation: curl ignores them, and they do not know your rules. A browser accepts ftp://example.com/file as a URL and three spaces as a title. The server accepts neither.
A form that shows its errors
AddForm now takes the form state. LinksPage passes it through.
templ LinksPage(links []Link, f Filter, form LinkForm) {
@Page("Reading list") {
@AddForm(form, false)
@SearchForm(f)
@LinkList(links)
}
}
// AddForm renders the form for a new link. With oob set, htmx swaps it over
// the form already on the page, wherever the main response goes.
templ AddForm(f LinkForm, oob bool) {
<form
id="add-link"
action="/links"
method="post"
hx-post="/links"
hx-target="#links"
hx-swap="afterbegin"
hx-status:422="target:#add-link swap:outerHTML"
if oob {
hx-swap-oob="true"
}
>
<label>
URL
<input type="url" name="url" value={ f.URL } required aria-invalid?={ f.Errors["url"] != "" }/>
@fieldError(f.Errors["url"])
</label>
<label>
Title
<input type="text" name="title" value={ f.Title } required aria-invalid?={ f.Errors["title"] != "" }/>
@fieldError(f.Errors["title"])
</label>
<label>
Note
<textarea name="note" rows="2" aria-invalid?={ f.Errors["note"] != "" }>{ f.Note }</textarea>
@fieldError(f.Errors["note"])
</label>
<button type="submit">Add link</button>
</form>
}
templ fieldError(msg string) {
if msg != "" {
<small class="error">{ msg }</small>
}
}Every field is rendered with the submitted value, and a message appears under each field that has one. Reading a missing key from a nil map returns the empty string, so the zero value LinkForm{} renders a blank form with no errors. listLinks passes exactly that: in its last line, the call becomes LinksPage(links, f, LinkForm{}). The oob parameter and the hx-status attribute are explained below.
Status codes and htmx
func (a *app) createLink(w http.ResponseWriter, r *http.Request) {
form, ok := a.readLinkForm(w, r)
if !ok {
return
}
if !form.Validate() {
a.invalidForm(w, r, form)
return
}
l, err := a.store.Create(r.Context(), form.URL, form.Title, form.Note)
if err != nil {
a.serverError(w, r, err)
return
}
a.logger.Info("link created", "id", l.ID)
if isPartial(r) {
// The new item goes into the list. The blank form replaces the
// submitted one out of band.
a.render(w, r, http.StatusCreated, templ.Join(LinkItem(l), AddForm(LinkForm{}, true)))
return
}
http.Redirect(w, r, "/links", http.StatusSeeOther)
}
// invalidForm answers a rejected submission with 422 and the form, including
// the submitted values and the error messages.
func (a *app) invalidForm(w http.ResponseWriter, r *http.Request, form LinkForm) {
if isPartial(r) {
a.render(w, r, http.StatusUnprocessableEntity, AddForm(form, false))
return
}
links, err := a.store.List(r.Context(), Filter{})
if err != nil {
a.serverError(w, r, err)
return
}
a.render(w, r, http.StatusUnprocessableEntity, LinksPage(links, Filter{}, form))
}
// readLinkForm parses the request body into a LinkForm. It writes the error
// response itself and returns false if the body cannot be read.
func (a *app) readLinkForm(w http.ResponseWriter, r *http.Request) (LinkForm, bool) {
r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
if err := r.ParseForm(); err != nil {
a.fail(w, r, http.StatusBadRequest, "The form could not be read.")
return LinkForm{}, false
}
return LinkForm{
URL: r.PostForm.Get("url"),
Title: r.PostForm.Get("title"),
Note: r.PostForm.Get("note"),
}, true
}readLinkForm caps the body at 64 KiB with http.MaxBytesReader before parsing, so a client cannot make the server buffer an arbitrarily large form.
A rejected submission is answered with 422 Unprocessable Entity and the form. The status matters for anything that is not a person looking at the page: tests, logs, monitoring and curl can all tell a rejection from a success.
htmx 4 swaps every response into the page except 204 and 304. That includes 4xx and 5xx responses, a change from htmx 2, which did not swap error responses unless configured to. So the 422 body is used, which is what you want here, but it goes to the form’s normal target. With only the lesson 4 attributes, the form with its error messages was inserted at the top of the list, as a second <form id="add-link">.
The hx-status attribute fixes that for one status code. hx-status:422="target:#add-link swap:outerHTML" says: when the answer is a 422, replace the form itself instead of prepending to the list.
curl -i -H 'HX-Request-Type: partial' -d url=ftp://example.com/file -d 'title= ' localhost:8792/linksHTTP/1.1 422 Unprocessable Entity
Content-Type: text/html; charset=utf-8
Date: Sat, 28 Nov 2026 22:06:02 GMT
Content-Length: 554
<form id="add-link" action="/links" method="post" hx-post="/links" hx-target="#links" hx-swap="afterbegin" hx-status:422="target:#add-link swap:outerHTML"><label>URL <input type="url" name="url" value="ftp://example.com/file" required aria-invalid><small class="error">Enter a full http or https URL.</small></label> <label>Title <input type="text" name="title" value="" required aria-invalid><small class="error">Enter a title.</small></label> <label>Note <textarea name="note" rows="2"></textarea></label> <button type="submit">Add link</button></form>In the browser, the console reports the 422 as a failed resource load. That line comes from the browser, which logs every 4xx response to fetch. htmx has done its job.
Resetting the form
Lesson 4 cleared the form with this.reset(). That stopped being correct the moment the form could be re-rendered. reset() restores each field to its default value, which is its value attribute, and after a 422 swap those attributes hold the rejected input. Tested in the browser: submit an invalid form, correct it, submit again, and the URL field snapped back to ftp://example.com/file with both error messages still on screen.
So the hx-on attribute is gone, and the server sends a blank form along with the new item. An element in a response that carries hx-swap-oob="true" is taken out of the response and swapped over the element with the same id in the page, “out of band”. The rest of the response goes to the normal target. templ.Join concatenates the two components:
curl -s -H 'HX-Request-Type: partial' -d url=https://templ.guide/ -d 'title=templ docs' localhost:8792/links<li id="link-3"><a href="https://templ.guide/">templ docs</a> <small>templ.guide, Nov 29</small> <form action="/links/3/toggle" method="post" hx-post="/links/3/toggle" hx-target="closest li" hx-swap="outerHTML"><button type="submit">Mark read</button></form></li><form id="add-link" action="/links" method="post" hx-post="/links" hx-target="#links" hx-swap="afterbegin" hx-status:422="target:#add-link swap:outerHTML" hx-swap-oob="true"><label>URL <input type="url" name="url" value="" required></label> <label>Title <input type="text" name="title" value="" required></label> <label>Note <textarea name="note" rows="2"></textarea></label> <button type="submit">Add link</button></form>The <li> goes into the list. The form replaces the old one, values and messages included. No client code decides what “reset” means.
Clients without htmx
A plain form submission takes the other branch in both functions. On success the answer is 303 See Other and the browser fetches /links with a GET. This is the post/redirect/get pattern: the page the user ends up on is the result of a GET, so reloading it does not submit the form a second time.
curl -i -d url=https://alpinejs.dev/ -d title=Alpine localhost:8792/linksHTTP/1.1 303 See Other
Location: /links
Date: Sat, 28 Nov 2026 22:06:02 GMT
Content-Length: 0On failure there is no redirect, because the input and the messages would be lost on the way. The handler renders the whole page with status 422 and the form filled in.
The redirect must not be sent to htmx. fetch follows a 303 on its own, htmx never sees it, and what arrives is the full page from /links. When this was tried with the redirect sent unconditionally, a second copy of the list ended up nested inside the first.
Failures that are not the user’s fault
htmx swaps the other error responses too. With the lesson 4 code, clicking “Mark read” on a link that had been deleted in the meantime replaced its list item with the bare text 404 page not found. A 500 would land in the same spot. Errors need their own place. Add an element for them to the layout:
<main>
<p id="flash" role="alert"></p>
{ children... }
</main>Then route all error responses through one function in handlers.go:
func (a *app) storeError(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, ErrNotFound) {
a.notFound(w, r)
return
}
a.serverError(w, r, err)
}
func (a *app) notFound(w http.ResponseWriter, r *http.Request) {
a.fail(w, r, http.StatusNotFound, "That link no longer exists.")
}
func (a *app) serverError(w http.ResponseWriter, r *http.Request, err error) {
a.logger.Error("request failed", "method", r.Method, "path", r.URL.Path, "err", err)
a.fail(w, r, http.StatusInternalServerError, "Something went wrong on the server.")
}
// fail writes a plain-text error. For an htmx request it also redirects the
// swap to the #flash element, so the message does not replace a list item.
func (a *app) fail(w http.ResponseWriter, r *http.Request, status int, msg string) {
if isPartial(r) {
w.Header().Set("HX-Retarget", "#flash")
w.Header().Set("HX-Reswap", "innerHTML")
}
http.Error(w, msg, status)
}HX-Retarget and HX-Reswap are response headers with which the server overrides the target and swap that the markup asked for. Here they send the message into #flash, wherever the request came from. Replace the remaining http.NotFound(w, r) calls in the handlers with a.notFound(w, r), and the http.Error call in recoverPanic with a.fail(w, r, http.StatusInternalServerError, "Something went wrong on the server.").
curl -i -X POST -H 'HX-Request-Type: partial' localhost:8792/links/99/toggleHTTP/1.1 404 Not Found
Content-Type: text/plain; charset=utf-8
Hx-Reswap: innerHTML
Hx-Retarget: #flash
X-Content-Type-Options: nosniff
Date: Sat, 28 Nov 2026 22:06:02 GMT
Content-Length: 28
That link no longer exists.Go writes the header names in its canonical capitalization. HTTP header names are case-insensitive, and htmx reads them either way. In the browser, the same experiment as before now shows the message above the form and leaves the stale row alone.
Three rules at the end of the stylesheet style the new elements:
label { display: grid; }
.error, #flash { color: #b00020; }
#flash:empty { display: none; }The data still disappears with every restart. The next lesson puts it in SQLite.
Exercises
- The flash message stays until the page is reloaded. Clear it whenever a new htmx request starts by adding
hx-on::before:request="find('#flash').textContent = ''"to the<body>tag (findis an htmx helper available insidehx-on). A correct result: after a failed toggle shows the message, marking any other link removes it. - Add a rule to
Validatethat rejects URLs longer than 2000 characters. Sending such a URL with curl and theHX-Request-Type: partialheader should return 422 and a form containing your message. Sending it without the header should return 422 and a full page containing the same message. - Do the 422 retargeting from the server instead: remove the
hx-statusattribute and setHX-RetargetandHX-ReswapininvalidFormfor partial requests. A correct result behaves exactly as before in the browser: one form, errors next to the fields, list untouched. Decide which version you prefer and why. One keeps the decision next to the markup it affects, the other keeps it out of the markup.