Form

A simple form submission example with validation on blur

type 'htmgo' to see validation errors

Source Code

Copy
 1package snippets
 2
 3import (
 4	"github.com/maddalax/htmgo/framework/h"
 5	"github.com/maddalax/htmgo/framework/hx"
 6)
 7
 8func FormWithBlurValidation(ctx *h.RequestContext) *h.Partial {
 9	buttonClasses := "rounded items-center px-3 py-2 bg-slate-800 text-white w-full text-center"
10	validationPath := h.GetPartialPath(
11		Validate,
12	)
13	return h.NewPartial(
14		h.Form(
15			h.TriggerChildren(),
16			h.Id("my-form"),
17			// hx-swap: none is required so the traditional swap doesn't happen, only oob swap
18			h.NoSwap(),
19			h.PostPartial(SubmitFormExample),
20			h.Class("flex flex-col gap-2 max-w-[300px] mx-auto"),
21			h.LabelFor("name", "Your Name"),
22			h.Input(
23				"text",
24				h.Required(),
25				h.Class("p-4 rounded-md border border-slate-200"),
26				h.Name("name"),
27				h.Placeholder("Name"),
28				h.Post(validationPath, hx.BlurEvent),
29			),
30			h.Pf(
31				"type 'htmgo' to see validation errors",
32				h.Class("text-slate-600 text-sm"),
33			),
34			h.Div(
35				h.Id("name-error"),
36				h.Class("text-red-500"),
37			),
38			h.LabelFor("occupation", "Occupation"),
39			h.Input(
40				"text",
41				h.Required(),
42				h.Class("p-4 rounded-md border border-slate-200"),
43				h.Name("occupation"),
44				h.Placeholder("Software Developer"),
45			),
46			h.Button(
47				h.Type("submit"),
48				h.Class(buttonClasses),
49				h.Text("Submit"),
50			),
51		),
52	)
53}
54
55func Validate(ctx *h.RequestContext) *h.Partial {
56	name := ctx.FormValue("name")
57
58	if name == "htmgo" {
59		ctx.Response.WriteHeader(400)
60		return h.SwapPartial(
61			ctx,
62			h.Div(
63				h.Id("name-error"),
64				h.Text("Name is already taken"),
65				h.Class("p-4 bg-rose-400 text-white rounded-md"),
66			),
67		)
68	}
69
70	return h.EmptyPartial()
71}
72
73func SubmitFormExample(ctx *h.RequestContext) *h.Partial {
74
75	if !ctx.IsHttpPost() {
76		return h.EmptyPartial()
77	}
78
79	validate := Validate(ctx)
80
81	// if there is a validation error, swap it in
82	if !h.IsEmptyPartial(validate) {
83		return validate
84	}
85
86	// submit the form
87	return h.SwapPartial(
88		ctx,
89		h.Div(
90			h.Id("my-form"),
91			h.Text("Form submitted with name: "+ctx.FormValue("name")),
92		),
93	)
94}