Include MinValue as form attr and use name instead of id in template tags
1 files changed, 19 insertions(+), 20 deletions(-)

M formguard.go
M formguard.go +19 -20
@@ 3,7 3,6 @@ package formguard
 import (
 	"fmt"
 	"html/template"
-	"strings"
 
 	"github.com/labstack/echo/v4"
 	"hg.code.netlandish.com/~netlandish/gobwebs/validate"

          
@@ 11,17 10,15 @@ import (
 
 // Form ...
 type Form struct {
-	AntiSpam int `form:"antispam"`
+	AntiSpamField int
+	MinValue      int
 }
 
-// XXX hardcoded for now
-var FormGuardMinValue int = 5
-
 // Validate ...
-func (f *Form) Validate(c echo.Context) error {
+func (f *Form) Validate(c echo.Context, fieldName string) error {
 	errs := echo.FormFieldBinder(c).
 		FailFast(false).
-		Int("antispam", &f.AntiSpam).
+		Int(fieldName, &f.AntiSpamField).
 		BindErrors()
 	if errs != nil {
 		return validate.GetInputErrors(errs)

          
@@ 31,7 28,11 @@ func (f *Form) Validate(c echo.Context) 
 		return err
 	}
 
-	if f.AntiSpam < FormGuardMinValue {
+	if f.MinValue == 0 {
+		f.MinValue = 5
+	}
+
+	if f.AntiSpamField < f.MinValue {
 		return validate.InputErrors{"_global_": []string{"This operation is forbbiden."}}
 	}
 

          
@@ 39,8 40,12 @@ func (f *Form) Validate(c echo.Context) 
 }
 
 // ScriptJS ...
-func ScriptJS(ids ...string) template.HTML {
-	script := `<script>
+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);

          
@@ 51,7 56,7 @@ func ScriptJS(ids ...string) template.HT
 		  }
 		}
 	}
-	let field_ids = [<idsList>];
+	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]);

          
@@ 59,18 64,12 @@ func ScriptJS(ids ...string) template.HT
 		setTimeout("anti_spam()", 1000);
     }
     anti_spam();
-	</script>`
-	var idsList string
-	for _, id := range ids {
-		idsList += fmt.Sprintf("'%s',", id)
-	}
-	script = strings.Replace(script, "<idsList>", idsList, 1)
+	</script>`, nameList)
 	return template.HTML(script)
 }
 
 // InputHTML ...
-func InputHTML(id string) template.HTML {
-	input := "<input type='hidden' name='antispan' value='0' id='<elementID>'/>"
-	input = strings.Replace(input, "<elementID>", id, 1)
+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)
 }