From 21840d3efa2d5789ae53af0278cc72265d1184c6 Mon Sep 17 00:00:00 2001 From: Yader Velasquez Date: Mon, 19 Dec 2022 13:50:52 -0600 Subject: [PATCH] Init --- formguard.go | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++ go.mod | 3 ++ 2 files changed, 83 insertions(+) create mode 100644 formguard.go create mode 100644 go.mod diff --git a/formguard.go b/formguard.go new file mode 100644 index 0000000..c2b78cf --- /dev/null +++ b/formguard.go @@ -0,0 +1,80 @@ +package formguard + +import ( + "fmt" + "html/template" + + "github.com/labstack/echo/v4" + "hg.code.netlandish.com/~netlandish/gobwebs/validate" +) + +// Form ... +type Form struct { + AntiSpamField int + MinValue int + FieldName string +} + +// Validate ... +func (f *Form) Validate(c echo.Context) error { + if f.FieldName == "" { + f.FieldName = "antispam" + } + + errs := echo.FormFieldBinder(c). + FailFast(false). + Int(f.FieldName, &f.AntiSpamField). + BindErrors() + if errs != nil { + return validate.GetInputErrors(errs) + } + + if err := c.Validate(f); err != nil { + return err + } + + if f.MinValue == 0 { + f.MinValue = 5 + } + + if f.AntiSpamField < f.MinValue { + return validate.InputErrors{"_global_": []string{"This operation is forbbiden."}} + } + + return nil +} + +// ScriptJS ... +func ScriptJS(names ...string) template.HTML { + var nameList string + for _, name := range names { + nameList += fmt.Sprintf("'id_%s',", name) + } + script := fmt.Sprintf(``, nameList) + return template.HTML(script) +} + +// InputHTML ... +func InputHTML(name string) template.HTML { + input := fmt.Sprintf("", name, name) + return template.HTML(input) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..3513a39 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module hg.code.netlandish.com/~netlandish/gobwebs-formguard + +go 1.19 -- 2.45.2