forms.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. Label string
  14. Value string
  15. Class string
  16. Error error
  17. Validators *ValidatorsList
  18. }
  19. /* SetValidators configures validators list in form field */
  20. func (f FormField) SetValidators(validators *ValidatorsList) FormField {
  21. f.Validators = validators
  22. return f
  23. }
  24. /* SetLabel configures form label */
  25. func (f FormField) SetLabel(label string) FormField {
  26. f.Label = label
  27. return f
  28. }
  29. /* SetClass configures class name in form field */
  30. func (f FormField) SetClass(class string) FormField {
  31. f.Class = class
  32. return f
  33. }
  34. /* GetString returns FormField.Value as string */
  35. func (f FormField) GetString() string {
  36. return f.Value
  37. }
  38. /* GetInt returns FormField.Value as int */
  39. func (f FormField) GetInt() (int, error) {
  40. return strconv.Atoi(f.Value)
  41. }
  42. /* Int converts FormField.Value to integer value and ignores errors */
  43. func (f FormField) Int() int {
  44. if result, err := strconv.Atoi(f.Value); err == nil {
  45. return result
  46. }
  47. return 0
  48. }
  49. /* GetFloat returns FormField.Value as float */
  50. func (f FormField) GetFloat() (float64, error) {
  51. return strconv.ParseFloat(f.Value, 64)
  52. }
  53. /* Float converts FormField.Value to float and ignores errors */
  54. func (f FormField) Float() float64 {
  55. if result, err := strconv.ParseFloat(f.Value, 64); err == nil {
  56. return result
  57. }
  58. return 0.0
  59. }
  60. /* GetBool returns boolean value for checkbox fields */
  61. func (f FormField) GetBool() (bool, error) {
  62. /* placeholder */
  63. return false, nil
  64. }
  65. /* GetChecked returns true if checkbox has been checked and its value is "on" */
  66. func (f FormField) GetChecked() bool {
  67. return f.Value == "on"
  68. }