-
Notifications
You must be signed in to change notification settings - Fork 14
/
validation.go
78 lines (68 loc) · 1.93 KB
/
validation.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 form
import (
"net/http"
"path/filepath"
"regexp"
"strconv"
)
var (
validMobile = regexp.MustCompile(`^[\d]{11}$`)
validEmail = regexp.MustCompile(`^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$`)
)
// ValidateString will validate a string field for the form, if the re pattern is passing in, validation would be check
// on the regexp.MatchString, else only check for emptyness.
func ValidateString(r *http.Request, name string, re ...*regexp.Regexp) bool {
value := r.FormValue(name)
if len(re) == 0 {
return value != ""
}
return re[0].MatchString(value)
}
// ValidateEmail will validate a form field and check if it is an Email address.
func ValidateEmail(r *http.Request, name string) bool {
return ValidateString(r, name, validEmail)
}
// ValidateMobile will validate a form field and check if it is a mobile phone number (for China format, e.g. "13911119999")
func ValidateMobile(r *http.Request, name string) bool {
return ValidateString(r, name, validMobile)
}
// ValidateInt will avlidate a form field and check if it is a int number or you can pass in the min/max value for this
func ValidateInt(r *http.Request, name string, minmax ...int64) bool {
value := r.FormValue(name)
if value == "" {
return false
}
if intValue, err := strconv.ParseInt(value, 10, 64); err != nil {
return false
} else {
if len(minmax) > 0 {
if intValue < minmax[0] {
return false
}
}
if len(minmax) > 1 {
if intValue > minmax[1] {
return false
}
}
}
return true
}
// ValidateFileExts will validate a form field and check if it's file extension in the allowed list.
func ValidateFileExts(r *http.Request, name string, exts ...string) bool {
if len(exts) == 0 {
return true
}
_, header, err := r.FormFile(name)
if err != nil {
return false
}
ext, allowed := filepath.Ext(header.Filename), false
for _, allowExt := range exts {
if ext == allowExt {
allowed = true
break
}
}
return allowed
}