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.

61 lines
1.4 KiB

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