Forms
One rule set for the browser constraints, the live validation and the submit.
A form input is a route type with a Rules method. The same rules give four checks: the browser constraints, the live validation of one field, the submit, and the form with no JavaScript.
gx new slice account
gx new form account/SignupThe input and its rules
A rule points at a field with a pointer. When you rename the field, the rule and the view change with it or stop the build.
A nested struct binds with a dotted name, such as address.city. A file is a gx.File field.
// Package route holds the route types of the account slice. A route
// package holds only route types.
package route
import "github.com/alternayte/gx"
// Index is the first page of the slice.
type Index struct {
gx.Route `GET /account`
}
// SignupPage is the page that shows the signup form.
type SignupPage struct {
gx.Route `GET /account/signup`
}
// Address is a nested part of the form.
type Address struct {
City string
}
// Signup is the input of the signup form.
type Signup struct {
gx.Route `POST /account/signup`
Email string
Age int
Plan string
Terms bool
Avatar gx.File
Address Address
}
// Rules holds the checks of the form.
func (in *Signup) Rules() gx.Rules {
return gx.Rules{
gx.Field(&in.Email, gx.Required, gx.Email, gx.MaxLen(254)),
gx.Field(&in.Age, gx.Min(18), gx.Max(120)),
gx.Field(&in.Plan, gx.OneOf("free", "team")),
gx.Field(&in.Terms, gx.True("terms.required")),
gx.Field(&in.Avatar, gx.MaxSize(1<<20), gx.Accept("image/*")),
gx.Field(&in.Address.City, gx.Required),
}
}The rules
| Rule | Check | Browser attribute |
|---|---|---|
gx.Required |
The value is not empty. | required |
gx.Email |
The value is an email address. | type="email" |
gx.IsURL |
The value is a URL. | type="url" |
gx.MinLen(n), gx.MaxLen(n) |
The length of the text. | minlength, maxlength |
gx.Min(n), gx.Max(n) |
The range of a number. | min, max |
gx.Pattern(re) |
The text matches a regular expression. | pattern |
gx.OneOf(values...) |
The value is one of a list. | none |
gx.True(key) |
A checkbox is on. | none |
gx.MaxSize(n), gx.Accept(types...) |
The size and the type of a file. | accept |
gx.Each(rule) |
The rule passes for each item of a slice. | none |
gx.Check(fn), gx.CheckCtx(fn) |
A function on the server. | none |
A rule with no browser attribute runs on the server only.
The handler
gx.Form(fn, view) registers the form. The handler gets a pointer to the input, and it runs only when each rule passes.
package account
import (
"github.com/alternayte/gx"
"acme/account/route"
)
// Signup receives the signup form.
var Signup = gx.Form(func(c *gx.Ctx, in *route.Signup) error {
if in.Email == "taken@example.com" {
return gx.FieldError(&in.Email, "email.taken")
}
// The toast shows on the page of the redirect.
c.Toast("Welcome", gx.ToastSuccess)
return c.Redirect(route.Index{})
}, SignupView)
// SignupPage shows the empty form.
var SignupPage = gx.Page(func(c *gx.Ctx, in route.SignupPage) (SignupViewProps, error) {
return Signup.Props(&route.Signup{Plan: "free"}), nil
}, SignupView)The view
Gx generates route.SignupForm with one typed field for each input field. A field has ID, Name, Value, Error and Attrs().
p.F.Attrs()gives the form element its id, method, action and marker.p.F.Email.Attrs()gives a control its name, id, value, constraints and ARIA state.- A registry control takes the attributes of a field through its
Attrsprop:<input.Input type="email" attrs={p.F.Email.Attrs()} />. The name and the id of the field replace the empty defaults of the component. data-gx-validate="blur"or"input"checks one field on the server and patches only its error.
package account
import "acme/account/route"
props {
// F is the typed form: one field per input field.
F route.SignupForm
}
<gx.Head title="Sign up" />
<h1 class="text-2xl font-semibold">Sign up</h1>
<form {...p.F.Attrs()} class="mt-4 grid max-w-sm gap-2">
<label for={p.F.Email.ID}>Email</label>
<input {...p.F.Email.Attrs()} type="email" data-gx-validate="blur" class="rounded-md border border-border px-3 py-2" />
<p id={p.F.Email.ID + "-error"} role="alert" class="text-sm text-destructive">{p.F.Email.Error}</p>
<label for={p.F.Age.ID}>Age</label>
<input {...p.F.Age.Attrs()} type="number" class="rounded-md border border-border px-3 py-2" />
<p id={p.F.Age.ID + "-error"} role="alert" class="text-sm text-destructive">{p.F.Age.Error}</p>
<label for={p.F.Plan.ID}>Plan</label>
<select name={p.F.Plan.Name} id={p.F.Plan.ID} class="rounded-md border border-border px-3 py-2">
<option value="free" selected={p.F.Plan.Value == "free"}>Free</option>
<option value="team" selected={p.F.Plan.Value == "team"}>Team</option>
</select>
<label for={p.F.Address.City.ID}>City</label>
<input {...p.F.Address.City.Attrs()} type="text" class="rounded-md border border-border px-3 py-2" />
<p id={p.F.Address.City.ID + "-error"} role="alert" class="text-sm text-destructive">{p.F.Address.City.Error}</p>
<label for={p.F.Avatar.ID}>Picture</label>
<input {...p.F.Avatar.Attrs()} type="file" />
<p id={p.F.Avatar.ID + "-error"} role="alert" class="text-sm text-destructive">{p.F.Avatar.Error}</p>
<label class="flex items-center gap-2">
<input {...p.F.Terms.Attrs()} type="checkbox" />
I accept the terms
</label>
<p id={p.F.Terms.ID + "-error"} role="alert" class="text-sm text-destructive">{p.F.Terms.Error}</p>
<button type="submit" class="rounded-md bg-primary px-3 py-1.5 text-sm text-primary-foreground">Create account</button>
</form>/account/signup
The page of the sample app
A form with a file field gets enctype="multipart/form-data". Gx checks the size before the handler runs, and it does not read a file that is too large into memory.
A password does not come back into the page. The render writes no value attribute on an <input type="password">, from a field, a spread or a prop. This is true for the page of a failed submit, for the patch of a failed submit and for the 422 page with no JavaScript. The reader types the password again. gx check gives the hint GX2024 for a password input with a value.
One form for each row
A page can show one form of a route type for each row of a list, such as a revoke button for each session. Give the route type a key field: the tag gx:"key" on the field that is different for each row, for example Session string `gx:"key"` in the route type Revoke.
- The id of the form is
revoke-form-<key>. - The id of each field is
revoke-<key>-<field>, for examplerevoke-s1-session. - Letters and digits of the key stay. Each other byte of the key becomes
_and two lower-case hex digits. The keya.1givesrevoke-form-a_2e1, and the keya-1givesrevoke-form-a_2d1. - So two different keys always give different ids.
- A form with an empty key has the ids of a form with no key field.
Put the key field in the form, for example as a hidden input: <input type="hidden" {...s.Session.Attrs()} />. A failed submit binds the same key, so the server renders the form with the same ids. The patch then goes to the form that the reader submitted. Live validation sends the key too.
A route type has one key field at most. gx generate reports GX3007 for two key fields. gx check gives the hint GX2023 for a form in a loop whose route type has no key field.
The answers of a submit
| Case | With JavaScript | Without JavaScript |
|---|---|---|
| A rule fails | Only the form element is patched. | Status 422 with the full page. |
The handler returns gx.FieldError |
The form shows that error. | The same, with status 422. |
| The handler redirects | The browser goes to the page. | Status 303. |
| A middleware answers with a page, such as a redirect to a sign-in page | The browser loads that page. | The browser shows that page. |
A JavaScript submit sends the name and the value of the button that submitted the form, as the browser does with no JavaScript. A form with two buttons name="op" gets the value of the button that the reader clicked.
The runtime sends a form one time. It never posts the form again after an answer:
- An answer of the adapter, of any status, is applied as patches.
- An HTML answer that the adapter did not write loads the address of the answer in full.
- A plain-text answer, such as the 403 of the CSRF check or the 500 of a panic, shows an error toast. A network failure shows the same toast. The page stays, and the handler ran one time at most.
The text of the error toast is the message of the key gx.form_failed. The toast component of the app renders it. The toast shows in the toaster of the page, such as gx.Toaster(). On a page with no toaster, the runtime adds a polite live region at the bottom of the page for the toast.
A toast that the handler queues before a redirect shows on the next page, with JavaScript and without it. The Signup handler above shows one. Gx puts the toasts in the cookie gx_flash. The server signs the cookie with the app secret. The cookie is HttpOnly, and it lives for 10 seconds.
The next page reads the cookie one time and clears it. gx.Toaster() shows the toasts in that page. A page with no gx.Toaster() drops them. A cookie that the server did not sign shows no toast.
A value of the wrong type, such as text in the age field, is a field error with the key invalid. It is not a 400.
A submit in flight
With JavaScript, a submit that takes more than 100 ms sets aria-busy="true" on the form and on the button that submitted it. The mark goes when the answer arrives or fails. A second submit of the same form before the answer arrives sends no request, so a double click sends one request. Style the pending state with CSS:
button[aria-busy="true"] { opacity: 0.6; cursor: progress; }An element that invokes an action with an on: directive gets the same mark. Read Actions and signals.
An optimistic form
optimistic:submit on a form element that spreads p.F.Attrs() changes signals before the request of the form, for example <form {...p.F.Attrs()} optimistic:submit={$Halted = true}>. The form needs no on:submit handler.
The runtime runs the statements just before it sends the form. When the submit fails, the runtime puts the values of before back. A failure is a rule failure, a gx.FieldError, a handler error, an error status or no network. Read Optimistic updates.
A form in a dialog
Give the form or its submit button data-gx-close="success" to close the dialog when the submit succeeds. The submit goes to the action of the form. The runtime closes the nearest dialog or popover when the answer arrives with a status of 2xx and no error mark.
- A rule failure or a
gx.FieldErrorkeeps the dialog open. The form shows the error. - A handler error keeps the dialog open. The error toast shows.
data-gx-closewith no value closes the dialog and sends nothing.
For example, write <form {...p.F.Attrs()} data-gx-close="success"> for the form of a confirm dialog.
The server marks the answer of a field error or a handler error with the header Gx-Error. The answer has the status 200, so that the patch or the toast reaches the page.
Messages
A message is a key with an English default. gx.SetTranslator replaces the text for each key.
package account
import "github.com/alternayte/gx"
// UseShortMessages replaces two default messages.
func UseShortMessages() {
gx.SetTranslator(func(key, fallback string) string {
switch key {
case "required":
return "Required."
case "email.taken":
return "This email has an account."
}
return fallback
})
}Repeated fields
A slice of structs binds with an index in the name, such as addresses[0].city. The generated field of the slice has an Each method that renders one row for each item. Add and remove a row with an action that patches the list.
Cross-site requests
Each form and each action passes the cross-origin check of Go net/http. A browser that sends no Fetch Metadata needs a token, and the Gx runtime adds it.