-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
101 lines (71 loc) · 1.84 KB
/
validator.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package happyngine
import (
"github.com/asaskevich/govalidator"
"regexp"
"strconv"
"time"
)
type FormValidatorHandler func(*Context, FormElementInterface)
func RegexpFormValidator(pattern string) FormValidatorHandler {
return func(c *Context, e FormElementInterface) {
r := regexp.MustCompile(pattern)
if !r.MatchString(e.FormValue()) {
c.AddError(400, e.Error())
}
}
}
func IsEqual(refs ...string) FormValidatorHandler {
return func(c *Context, e FormElementInterface) {
for _, ref := range refs {
if ref == e.FormValue() {
return
}
}
c.AddError(400, e.Error())
}
}
func IsEmail() FormValidatorHandler {
return RegexpFormValidator(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]+$`)
}
func IsFloat() FormValidatorHandler {
return func(c *Context, e FormElementInterface) {
if !govalidator.IsFloat(e.FormValue()) {
c.AddError(400, e.Error())
}
v, _ := strconv.ParseFloat(e.FormValue(), 64)
e.SetValue(v)
}
}
func IsInteger() FormValidatorHandler {
return func(c *Context, e FormElementInterface) {
RegexpFormValidator(`^(-|)[0-9]+$`)(c, e)
if c.HasErrors() {
return
}
// We don't check errors because of the previous regexp
i, _ := strconv.ParseInt(e.FormValue(), 10, 64)
e.SetValue(i)
}
}
func IsUInteger() FormValidatorHandler {
return func(c *Context, e FormElementInterface) {
RegexpFormValidator(`^[0-9]+$`)(c, e)
if c.HasErrors() {
return
}
// We don't check errors because of the previous regexp
i, _ := strconv.ParseUint(e.FormValue(), 10, 64)
e.SetValue(i)
}
}
func IsDate() FormValidatorHandler {
return func(c *Context, e FormElementInterface) {
_, err := time.Parse("2006-01-02", e.FormValue())
if err != nil {
c.AddError(400, e.Error())
}
}
}
func IsUUID() FormValidatorHandler {
return RegexpFormValidator(`^[a-f\d]{8}(-[a-f\d]{4}){3}-[a-f\d]{12}?$`)
}