package formparser import ( "errors" "fmt" "log" "time" ) // String parses a string, returning an error if it's outside the range of min,max. It still // sets the value so that it can be used for the view model. It would be bad if the user lost // a really long page because of the length limit func String(value string, target *string, min, max int) error { *target = value if len(value) < min || len(value) > max { return fmt.Errorf("not between %d and %d", min, max) } return nil } // Select sets the targer if the given form value is inside the list. It will skip if optional // is set and the value is empty func Select(value string, target *string, allowedValues []string, optional bool) error { if value == "" { if !optional { return errors.New("no option selected") } return nil } log.Println(value, allowedValues) for _, allowedValue := range allowedValues { if value == allowedValue { *target = value return nil } } return errors.New("not a valid option") } // Date parses a date, returning an error if it's missing (and not optional) and if it // cannot be parsed according to RFC3339 func Date(value string, target *time.Time, optional bool) error { if value == "" { if optional { return nil } return errors.New("missing") } date, err := time.Parse(time.RFC3339, value) if err != nil { return errors.New("an invalid date") } *target = date return nil }