-
Notifications
You must be signed in to change notification settings - Fork 1
/
validator.go
86 lines (72 loc) · 1.73 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
package MicroGO
import (
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/asaskevich/govalidator"
)
type Validation struct {
Data url.Values
Errors map[string]string
}
func (m *MicroGo) Validator(data url.Values) *Validation {
return &Validation{
Errors: make(map[string]string),
Data: data,
}
}
func (v *Validation) Valid() bool {
return len(v.Errors) == 0
}
func (v *Validation) AddError(key, message string) {
if _, exists := v.Errors[key]; !exists {
v.Errors[key] = message
}
}
func (v *Validation) Has(field string, r *http.Request) bool {
x := r.Form.Get(field)
return x != ""
}
func (v *Validation) Required(r *http.Request, fields ...string) {
for _, field := range fields {
value := r.Form.Get(field)
if strings.TrimSpace(value) == "" {
v.AddError(field, "This field cannot be blank")
}
}
}
func (v *Validation) Check(ok bool, key, message string) {
if !ok {
v.AddError(key, message)
}
}
func (v *Validation) IsEmail(field, value string) {
if !govalidator.IsEmail(value) {
v.AddError(field, "Invalid email address")
}
}
func (v *Validation) IsInt(field, value string) {
_, err := strconv.Atoi(value)
if err != nil {
v.AddError(field, "This field must be an integer")
}
}
func (v *Validation) IsFloat(field, value string) {
_, err := strconv.ParseFloat(value, 64)
if err != nil {
v.AddError(field, "This field must be a floating point number")
}
}
func (v *Validation) IsDateISO(field, value string) {
_, err := time.Parse("2006-01-02", value)
if err != nil {
v.AddError(field, "This field must be a date in the form of YYYY-MM-DD")
}
}
func (v *Validation) NoSpaces(field, value string) {
if govalidator.HasWhitespace(value) {
v.AddError(field, "Spaces are not permitted")
}
}