forms.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package form
  2. import (
  3. "context"
  4. "strconv"
  5. )
  6. // ValidatorFunc defines a function for FormField data validation
  7. type ValidatorFunc func(FormField, context.Context) error
  8. // ValidatorsList defines a list of ValidatorFunc
  9. type ValidatorsList []ValidatorFunc
  10. // A general purpose form field struct
  11. type FormField struct {
  12. Name string
  13. Value string
  14. Error error
  15. Validators *ValidatorsList
  16. }
  17. // GetString returns FormField.Value as string
  18. func (f FormField) GetString() string {
  19. return f.Value
  20. }
  21. // GetInt returns FormField.Value as int
  22. func (f FormField) GetInt() (int, error) {
  23. return strconv.Atoi(f.Value)
  24. }
  25. // GetFloat returns FormField.Value as float
  26. func (f FormField) GetFloat() (float64, error) {
  27. return strconv.ParseFloat(f.Value, 64)
  28. }
  29. // GetBool returns boolean value for checkbox fields
  30. func (f FormField) GetBool() (bool, error) {
  31. // placeholder
  32. return false, nil
  33. }
  34. // GetChecked returns true if checkbox has been selected
  35. // only works if checkbox value is "on" when selected
  36. func (f FormField) GetChecked() bool {
  37. return f.Value == "on"
  38. }