forms.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 checked and its value is "on" */
  49. func (f FormField) GetChecked() bool {
  50. return f.Value == "on"
  51. }