-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathvalidator.go
More file actions
202 lines (172 loc) · 4.81 KB
/
validator.go
File metadata and controls
202 lines (172 loc) · 4.81 KB
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package limen
import (
"fmt"
"net/http"
"regexp"
"slices"
"strings"
)
type ValidationError struct {
Field string
Message string
formatErrorMessage bool
}
func (e *ValidationError) Error() string {
if e.Field != "" && e.formatErrorMessage {
return fmt.Sprintf("%s %s", e.Field, e.Message)
}
return e.Message
}
type Errors struct {
errors []*ValidationError
}
func (e *Errors) Error() string {
if len(e.errors) == 0 {
return ""
}
if len(e.errors) == 1 {
return e.errors[0].Error()
}
messages := make([]string, len(e.errors))
for i, err := range e.errors {
messages[i] = err.Error()
}
return strings.Join(messages, "; ")
}
func (e *Errors) Add(field, message string, formatErrorMessage bool) {
e.errors = append(e.errors, &ValidationError{
Field: field,
Message: message,
formatErrorMessage: formatErrorMessage,
})
}
func (e *Errors) HasErrors() bool {
return len(e.errors) > 0
}
func (e *Errors) GetErrors() []*ValidationError {
return e.errors
}
type Validator struct {
errors *Errors
}
func NewValidator() *Validator {
return &Validator{
errors: &Errors{},
}
}
func (v *Validator) Validate() error {
if v.errors.HasErrors() {
return v.errors
}
return nil
}
func (v *Validator) RequiredString(field string, value any) *Validator {
if value == nil {
v.errors.Add(field, "is required", true)
return v
}
valueString, ok := value.(string)
if !ok || (ok && strings.TrimSpace(valueString) == "") {
v.errors.Add(field, "is required", true)
}
return v
}
func (v *Validator) MinLength(field, value string, minLen int) *Validator {
if len(value) < minLen {
v.errors.Add(field, fmt.Sprintf("must be at least %d characters", minLen), true)
}
return v
}
func (v *Validator) MaxLength(field, value string, maxLen int) *Validator {
if len(value) > maxLen {
v.errors.Add(field, fmt.Sprintf("must be at most %d characters", maxLen), true)
}
return v
}
func (v *Validator) Length(field, value string, length int) *Validator {
if len(value) != length {
v.errors.Add(field, fmt.Sprintf("must be exactly %d characters", length), true)
}
return v
}
func (v *Validator) Email(field string, value any) *Validator {
if value == nil || value == "" {
return v
}
emailRegex := `^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`
matched, err := regexp.MatchString(emailRegex, value.(string))
if err != nil || !matched {
v.errors.Add(field, "must be a valid email address", true)
}
return v
}
func (v *Validator) Custom(field string, fn func() error, formatErrorMessage bool) *Validator {
err := fn()
if err != nil {
v.errors.Add(field, err.Error(), formatErrorMessage)
}
return v
}
func (v *Validator) URL(field, value string) *Validator {
if value == "" {
return v // Empty URLs are handled by RequiredString()
}
urlRegex := `^https?://[^\s/$.?#].[^\s]*$`
matched, err := regexp.MatchString(urlRegex, value)
if err != nil || !matched {
v.errors.Add(field, "must be a valid URL", true)
}
return v
}
func (v *Validator) In(field, value string, allowed []string) *Validator {
if slices.Contains(allowed, value) {
return v
}
v.errors.Add(field, fmt.Sprintf("must be one of: %s", strings.Join(allowed, ", ")), true)
return v
}
func (v *Validator) Contains(field, value, substr string) *Validator {
if !strings.Contains(value, substr) {
v.errors.Add(field, fmt.Sprintf("must contain '%s'", substr), true)
}
return v
}
func (v *Validator) ContainsAny(field, value, chars string) *Validator {
if !strings.ContainsAny(value, chars) {
v.errors.Add(field, fmt.Sprintf("must contain at least one of: %s", chars), true)
}
return v
}
func (v *Validator) NotContains(field, value, substr string) *Validator {
if strings.Contains(value, substr) {
v.errors.Add(field, fmt.Sprintf("must not contain '%s'", substr), true)
}
return v
}
func (v *Validator) Matches(field, value, pattern string) *Validator {
matched, err := regexp.MatchString(pattern, value)
if err != nil {
v.errors.Add(field, "invalid pattern", true)
return v
}
if !matched {
v.errors.Add(field, "does not match required format", true)
}
return v
}
// ValidateJSON decodes the JSON body of the request and validates it using the validateFunc.
// It returns the decoded data if the validation succeeds, otherwise it returns nil and an error is written to the response.
func ValidateJSON(w http.ResponseWriter, r *http.Request, responder *Responder, validateFunc func(*Validator, map[string]any) *Validator) map[string]any {
body := GetJSONBody(r)
if len(body) == 0 || body == nil {
responder.Error(w, r, NewLimenError("empty JSON body", http.StatusBadRequest, nil))
return nil
}
v := NewValidator()
validateFunc(v, body)
if err := v.Validate(); err != nil {
responder.Error(w, r, NewLimenError(err.Error(), http.StatusUnprocessableEntity, nil))
return nil
}
return body
}