The backend for the AiteStory website
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.4 KiB

7 years ago
7 years ago
7 years ago
7 years ago
  1. package formparser
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "time"
  7. )
  8. // String parses a string, returning an error if it's outside the range of min,max. It still
  9. // sets the value so that it can be used for the view model. It would be bad if the user lost
  10. // a really long page because of the length limit
  11. func String(value string, target *string, min, max int) error {
  12. *target = value
  13. if len(value) < min || len(value) > max {
  14. return fmt.Errorf("not between %d and %d", min, max)
  15. }
  16. return nil
  17. }
  18. // Select sets the targer if the given form value is inside the list. It will skip if optional
  19. // is set and the value is empty
  20. func Select(value string, target *string, allowedValues []string, optional bool) error {
  21. if value == "" {
  22. if !optional {
  23. return errors.New("no option selected")
  24. }
  25. return nil
  26. }
  27. log.Println(value, allowedValues)
  28. for _, allowedValue := range allowedValues {
  29. if value == allowedValue {
  30. *target = value
  31. return nil
  32. }
  33. }
  34. return errors.New("not a valid option")
  35. }
  36. // Date parses a date, returning an error if it's missing (and not optional) and if it
  37. // cannot be parsed according to RFC3339
  38. func Date(value string, target *time.Time, optional bool) error {
  39. if value == "" {
  40. if optional {
  41. return nil
  42. }
  43. return errors.New("missing")
  44. }
  45. date, err := time.Parse(time.RFC3339, value)
  46. if err != nil {
  47. return errors.New("an invalid date")
  48. }
  49. *target = date
  50. return nil
  51. }