go-form-demo/form/contact.go

82 lines
2.2 KiB
Go

package form
import (
"net/http"
"gitnet.fr/deblan/go-form/form"
"gitnet.fr/deblan/go-form/validation"
)
type Contact struct {
Name string `field:"lowerCamel"`
Email string `field:"lowerCamel"`
Topic string `field:"lowerCamel"`
Message string `field:"lowerCamel"`
}
func CreateContactForm(isBoostrap bool) *form.Form {
var rowAttr form.Attrs
var btnAttr form.Attrs
formAttr := form.Attrs{"id": "contact-form"}
if isBoostrap {
rowAttr = form.Attrs{"class": "col-12"}
formAttr["class"] = "row"
btnAttr = form.Attrs{"class": "btn-primary"}
}
topics := form.NewChoices([]string{"I have a question", "Report a bug"}).
WithLabelBuilder(func(key int, item any) string {
return item.(string)
})
return form.NewForm(
form.NewFieldText("name").
WithOptions(
form.NewOption("label", "Your name"),
form.NewOption("required", true),
form.NewOption("row_attr", rowAttr),
form.NewOption("label_attr", form.Attrs{"class": "required"}),
).
WithConstraints(validation.NewNotBlank()),
form.NewFieldMail("email").
WithOptions(
form.NewOption("label", "Your e-mail"),
form.NewOption("required", true),
form.NewOption("row_attr", rowAttr),
form.NewOption("label_attr", form.Attrs{"class": "required"}),
).
WithConstraints(
validation.NewNotBlank(),
validation.NewMail(),
),
form.NewFieldChoice("topic").
WithOptions(
form.NewOption("label", "Topic"),
form.NewOption("empty_choice_label", ""),
form.NewOption("choices", topics),
),
form.NewFieldTextarea("message").
WithOptions(
form.NewOption("label", "Message"),
form.NewOption("required", true),
form.NewOption("row_attr", rowAttr),
form.NewOption("label_attr", form.Attrs{"class": "required"}),
form.NewOption("attr", form.Attrs{"rows": "10"}),
form.NewOption("help_attr", form.Attrs{"class": "help"}),
form.NewOption("help", "Minimum 10 chars"),
).
WithConstraints(
validation.NewNotBlank(),
validation.NewLength().WithMin(10),
),
form.NewSubmit("").
WithData("Send").
WithOptions(form.NewOption("attr", btnAttr)),
).
End().
WithOptions(form.NewOption("attr", formAttr)).
WithName("contact").
WithMethod(http.MethodPost)
}