-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
163 lines (136 loc) · 3.76 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package validator
import (
"errors"
"fmt"
"net"
"net/url"
"reflect"
"regexp"
"strings"
)
var (
// ErrNotImplement is returned when a method is not implemented.
ErrNotImplement = errors.New("not implement")
ErrEmailNotValid = errors.New("email not valid")
ErrEmptyField = errors.New("field is empty")
ErrNotEmptyField = errors.New("field not empty")
ErrUrlNotValid = errors.New("url not valid")
ErrIpAddressNotValid = errors.New("ip address not valid")
)
type ValidatorError interface {
Error() string
}
// Validator is the interface that wraps the Validate method.
type Validator interface {
IsEmail(input string) (ok bool, err error)
IsEmpty(input string) (ok bool, err error)
IsURL(input string) (ok bool, err error)
IsIP(input string) (ok bool, err error)
ValidateStruct(input any) errorMap
}
// validator is an implementation of Validator.
type validator struct {
errors errorMap
}
// New returns a new Validator.
func New() Validator {
return &validator{}
}
// IsEmail returns an error if the string is not a valid email address.
func (v *validator) IsEmail(email string) (ok bool, err error) {
if email == "" {
return false, ErrEmailNotValid
}
emailRegex := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
if !emailRegex.MatchString(email) {
return false, ErrEmailNotValid
}
return true, nil
}
// IsEmpty returns an error if the string is not empty.
func (v *validator) IsEmpty(input string) (ok bool, err error) {
if input == "" {
return false, ErrNotEmptyField
}
return true, nil
}
// IsURL returns an error if the string is not a valid URL.
func (v *validator) IsURL(input string) (ok bool, err error) {
parsedURL, err := url.Parse(input)
if err != nil {
return false, ErrUrlNotValid
}
if !parsedURL.IsAbs() {
return false, ErrUrlNotValid
}
return true, nil
}
// IsIP returns an error if the string is not a valid IP address.
func (v *validator) IsIP(input string) (ok bool, err error) {
parsedIP := net.ParseIP(input)
if parsedIP == nil {
return false, ErrIpAddressNotValid
}
return true, nil
}
func (v *validator) isInt(input any, fieldName string) (ok bool, err error) {
switch input.(type) {
case int:
return true, nil
default:
return false, fmt.Errorf("%v is not an integer", fieldName)
}
}
// ValidateStruct returns an a slice of errors if the struct input values have 'validate' tags.
func (v *validator) ValidateStruct(input any) errorMap {
st := reflect.TypeOf(input)
v.errors = make(errorMap)
inputKind := st.Kind()
if inputKind == reflect.Ptr {
st = st.Elem()
input = reflect.ValueOf(input).Elem().Interface()
}
for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
fieldName := field.Name
validateTag := field.Tag.Get("validate")
fieldValue := reflect.ValueOf(input).Field(i)
validateTags := strings.Split(validateTag, ",")
var actualValue any
switch fieldValue.Kind() {
case reflect.Interface:
actualValue = fieldValue.Interface()
default:
actualValue = fieldValue.String()
}
v.handleStructValidation(validateTags, strings.ToLower(fieldName), actualValue)
// TODO: handle embedded structs, slices, maps, etc.
}
if len(v.errors) == 0 {
return nil
}
return v.errors
}
func (v *validator) handleStructValidation(input []string, fieldName string, fieldValue any) {
for _, field := range input {
switch field {
case "required":
if fieldValue == "" {
v.errors[fieldName] = fmt.Errorf("%s is required", fieldName)
}
case "int":
if ok, err := v.isInt(fieldValue, fieldName); !ok {
v.errors[fieldName] = err
}
case "email":
if ok, err := v.IsEmail(fieldValue.(string)); !ok {
v.errors[fieldName] = err
}
case "url":
ok, err := v.IsURL(fieldValue.(string))
if !ok {
v.errors[fieldName] = err
}
}
}
}