Parcourir la source

Various changes:

    1. Add NewIntField constructor for integer input fields
    2. Make SetValidators accept list of ValidatorFunc instead of
       ValidatorsList
    3. Rename GetBool to GetChecked, returning true if checkbox is
       selected; also returns error (always nil)
    4. Add Checked method returning true if checkbox is selected
Bozhin Zafirov il y a 7 mois
Parent
commit
842bea0386
2 fichiers modifiés avec 26 ajouts et 10 suppressions
  1. 15 1
      constructors.go
  2. 11 9
      forms.go

+ 15 - 1
constructors.go

@@ -1,6 +1,9 @@
 package forms
 
-import "net/http"
+import (
+	"net/http"
+	"strconv"
+)
 
 /* strFromPtr converts string pointer to a string */
 func strFromPtr(str *string) (s string) {
@@ -19,6 +22,17 @@ func NewCharField(name string, value *string) *FormField {
 	}
 }
 
+/* Generate new integer type field */
+func NewIntField(name string, value int) *FormField {
+	field := FormField{
+		Name:  name,
+		Value: strconv.Itoa(value),
+		Kind:  "text",
+	}
+	field.AddValidator(ValidInt)
+	return &field
+}
+
 /* Generate new password field */
 func NewPasswordField(name string) *FormField {
 	return &FormField{

+ 11 - 9
forms.go

@@ -44,8 +44,10 @@ func (f *FormField) AddValidator(validator ValidatorFunc) *FormField {
 }
 
 /* SetValidators configures validators list in form field */
-func (f *FormField) SetValidators(validators ValidatorsList) *FormField {
-	f.Validators = validators
+func (f *FormField) SetValidators(validators ...ValidatorFunc) *FormField {
+	for _, validator := range validators {
+		f.AddValidator(validator)
+	}
 	return f
 }
 
@@ -129,18 +131,18 @@ func (f *FormField) Float() float64 {
 	return 0.0
 }
 
-/* GetBool returns boolean value for checkbox fields */
+/* GetBool returns true if checkbox is selected, always returns nil error */
 func (f *FormField) GetBool() (bool, error) {
-	/* placeholder */
-	return false, nil
+	/* if box is checked, it sends a non-empty value */
+	return len(f.Value) != 0, nil
 }
 
-/* GetChecked returns true if checkbox has been checked and its value is "on" */
-func (f *FormField) GetChecked() bool {
-	return f.Value == "on"
+/* Bool returns true if checkbox is selected, ignores errors */
+func (f *FormField) Bool() bool {
+	return len(f.Value) != 0
 }
 
-/* formFieldTemplate is a template to render FormField element in HTML format */
+/* fieldsTemplateStr is a template to render FormField element in HTML format */
 //go:embed fields.html
 var fieldsTemplateStr string