-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathisdate.go
78 lines (68 loc) · 2.1 KB
/
isdate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package validatorgo
import (
"time"
)
// IsDate formats
const (
StandardDateLayout = "2006-01-02"
SlashDateLayout = "2006/01/02"
DateTimeLayout = "2006-01-02 15:04:05"
ISO8601Layout = "2006-01-02T15:04:05"
ISO8601ZuluLayout = "2006-01-02T15:04:05Z"
ISO8601WithMillisecondsLayout = "2006-01-02T15:04:05.000Z"
)
var dateLayouts = [6]string{StandardDateLayout, SlashDateLayout, DateTimeLayout, ISO8601Layout, ISO8601ZuluLayout, ISO8601WithMillisecondsLayout}
var (
isDateOptsDefaultFormat string = StandardDateLayout
isDateOptsDefaultStrictMode bool = false
)
// IsDateOpts is used to configure IsDate
type IsDateOpts struct {
Format string
StrictMode bool
}
func dateMatchesAnyFormat(str string) bool {
for _, format := range dateLayouts {
_, err := time.Parse(format, str)
if err == nil {
return true
}
}
return false
}
// A Validator that checks if the string is a valid date. e.g. 2002-07-15.
//
// IsDateOpts is a struct which can contain the keys Format, StrictMode.
//
// Format: is a string and defaults to validatorgo.StandardDateLayout if "any" or no value is provided.
//
// StrictMode: is a boolean and defaults to false. If StrictMode is set to true, the validator will reject strings different from Format.
//
// ok := validatorgo.IsDate("2006-01-02", &validatorgo.IsDateOpts{})
// fmt.Println(ok) // true
// ok := validatorgo.IsDate("01/023/2006", &validatorgo.IsDateOpts{})
// fmt.Println(ok) // false
func IsDate(str string, opts *IsDateOpts) bool {
if opts == nil {
opts = setIsDateOptsToDefault()
}
switch opts.Format {
case StandardDateLayout, SlashDateLayout, DateTimeLayout, ISO8601Layout, ISO8601ZuluLayout, ISO8601WithMillisecondsLayout:
case "", "any":
opts.Format = isDateOptsDefaultFormat
default:
return false
}
if opts.StrictMode {
_, err := time.Parse(opts.Format, str)
return err == nil
} else {
return dateMatchesAnyFormat(str)
}
}
func setIsDateOptsToDefault() *IsDateOpts {
return &IsDateOpts{
Format: isDateOptsDefaultFormat,
StrictMode: isDateOptsDefaultStrictMode,
}
}