2 files changed, 83 insertions(+), 0 deletions(-)

A => formguard.go
A => go.mod
A => formguard.go +80 -0
@@ 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(`<script>
+	var update_field_value = function(field_id) {
+		if (document.getElementById(field_id)) {
+		  a = document.getElementById(field_id);
+		  if (isNaN(a.value) == true) {
+			a.value = 0;
+		  } else {
+			a.value = parseInt(a.value) + 1;
+		  }
+		}
+	}
+	let field_ids = [%s];
+    var anti_spam = function() {
+		for (var i=0, l=field_ids.length; i<l; i++) {
+			update_field_value(field_ids[i]);
+		}
+		setTimeout("anti_spam()", 1000);
+    }
+    anti_spam();
+	</script>`, nameList)
+	return template.HTML(script)
+}
+
+// InputHTML ...
+func InputHTML(name string) template.HTML {
+	input := fmt.Sprintf("<input type='hidden' name='%s' value='0' id='id_%s'/>", name, name)
+	return template.HTML(input)
+}

          
A => go.mod +3 -0
@@ 0,0 1,3 @@ 
+module hg.code.netlandish.com/~netlandish/gobwebs-formguard
+
+go 1.19