-
Notifications
You must be signed in to change notification settings - Fork 1
/
validator.go
90 lines (76 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
package january
import (
"github.com/asaskevich/govalidator"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
func (j *January) Validator(data url.Values) *Validation {
return &Validation{
Data: data,
Errors: make(map[string]string),
}
}
// Validation Easy validation for Form-Post
type Validation struct {
Data url.Values // this is standard for query params and form data
Errors map[string]string
}
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)
if x == "" {
return false
}
return true
}
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 float")
}
}
func (v *Validation) IsDateISO(field, value string) {
_, err := time.Parse("2023-09-12", 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")
}
}