package validation import ( "fmt" "time" "git.haelnorr.com/h/timefmt" ) type TimeField struct { FieldBase Value time.Time } func newTimeField(key string, format *timefmt.Format, g Getter) *TimeField { raw := g.Get(key) var startDate time.Time if raw != "" { var err error startDate, err = format.Parse(raw) if err != nil { g.AddCheck(newFailedCheck( "Invalid date/time format", fmt.Sprintf("%s should be in format %s", key, format.LDML()), )) } } return &TimeField{ Value: startDate, FieldBase: newField(key, g), } } func newTimeFieldInLocation(key string, format *timefmt.Format, loc *time.Location, g Getter) *TimeField { raw := g.Get(key) var startDate time.Time if raw != "" { var err error startDate, err = format.ParseInLocation(raw, loc) if err != nil { g.AddCheck(newFailedCheck( "Invalid date/time format", fmt.Sprintf("%s should be in format %s", key, format.LDML()), )) } } return &TimeField{ Value: startDate, FieldBase: newField(key, g), } } func (t *TimeField) Required() *TimeField { if t.Value.IsZero() { t.getter.AddCheck(newFailedCheck( "Date/Time not provided", fmt.Sprintf("%s must be provided", t.Key), )) } return t } // Optional will skip all validations if value is empty func (t *TimeField) Optional() *TimeField { if t.Value.IsZero() { t.optional = true } return t } func (t *TimeField) Before(limit time.Time) *TimeField { if !t.Value.Before(limit) { t.getter.AddCheck(newFailedCheck( "Date/Time invalid", fmt.Sprintf("%s must be before %s", t.Key, limit), )) } return t } func (t *TimeField) After(limit time.Time) *TimeField { if !t.Value.After(limit) { t.getter.AddCheck(newFailedCheck( "Date/Time invalid", fmt.Sprintf("%s must be after %s", t.Key, limit), )) } return t }