forms.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. // Int converts FormField.Value to integer value and ignores errors
  26. func (f FormField) Int() int {
  27. if result, err := strconv.Atoi(f.Value); err == nil {
  28. return result
  29. }
  30. return 0
  31. }
  32. // GetFloat returns FormField.Value as float
  33. func (f FormField) GetFloat() (float64, error) {
  34. return strconv.ParseFloat(f.Value, 64)
  35. }
  36. // Float converts FormField.Value to float and ignores errors
  37. func (f FormField) Float() float64 {
  38. if result, err := strconv.ParseFloat(f.Value, 64); err == nil {
  39. return result
  40. }
  41. return 0.0
  42. }
  43. // GetBool returns boolean value for checkbox fields
  44. func (f FormField) GetBool() (bool, error) {
  45. // placeholder
  46. return false, nil
  47. }
  48. // GetChecked returns true if checkbox has been selected
  49. // only works if checkbox value is "on" when selected
  50. func (f FormField) GetChecked() bool {
  51. return f.Value == "on"
  52. }