Repository navigation
Expand file tree
/
Copy pathdate.go
More file actions
69 lines (57 loc) · 1.49 KB
/
Copy pathdate.go
File metadata and controls
69 lines (57 loc) · 1.49 KB
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
package input
import "webtyp.com/fmt"
type date struct{ Base }
// Date creates a new date input instance.
func Date() Input {
d := &date{}
d.Numbers = true
d.Extra = []rune{'-'}
d.Minimum = 10
d.Maximum = 10
d.InitBase("", "", "date")
return d
}
// Validate validates YYYY-MM-DD format with leap year and day range checks.
func (d *date) Validate(value string) error {
if err := d.Permitted.Validate(d.name, value); err != nil {
return err
}
if len(value) != 10 {
return fmt.Err("Format", "Invalid", "2006-01-02")
}
for i, char := range value {
if i == 4 || i == 7 {
if char != '-' {
return fmt.Err("Format", "Invalid", "2006-01-02")
}
} else if char < '0' || char > '9' {
return fmt.Err("Format", "Invalid", "2006-01-02")
}
}
year, _ := fmt.Convert(value[:4]).Int()
month, _ := fmt.Convert(value[5:7]).Int()
day, _ := fmt.Convert(value[8:10]).Int()
if year < 1000 || year > 9999 {
return fmt.Err("Date", "Invalid", "year")
}
if month < 1 || month > 12 {
return fmt.Err("Month", "Invalid")
}
if day < 1 || day > d.monthDays(year)[month] {
return fmt.Err("Date", "Invalid")
}
return nil
}
func (d *date) monthDays(year int) [13]int {
feb := 28
if year%4 == 0 && year%100 != 0 || year%400 == 0 {
feb = 29
}
return [13]int{0, 31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
}
// Clone creates a new date input with the given parentID and name.
func (d *date) Clone(parentID, name string) Input {
c := *d
c.InitBase(parentID, name, "date")
return &c
}