-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidation.go
274 lines (224 loc) · 8.16 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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package validation
import (
"bytes"
"errors"
"fmt"
"reflect"
"strings"
"text/template"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"github.com/adnanbrq/validation/v2/helper"
"github.com/adnanbrq/validation/v2/rules"
)
// Validator struct contains custom and predefined validation rules along with error messages.
type Validator struct {
// customRules holds custom validation rules defined by the user.
customRules map[string]rules.Rule
// predefinedRules holds predefined validation rules provided by the validation package.
predefinedRules map[string]rules.Rule
// messages holds custom error messages for validation errors.
messages map[string]string
// fieldMessages holds custom error messages for validation errors of specific fields.
fieldMessages map[string]string
// failFast is used to skip upcoming rules if there already is a error
failFast bool
}
// ErrInvalidInput is returned when the input to the Validate method is not a struct.
var ErrInvalidInput = errors.New("the given input needs to be of type struct")
// getRule retrieves a custom or predefined rule by its name. It returns the rule or a the DefaultRule in case no rule was found
func (v *Validator) getRule(name string) rules.Rule {
if rule, found := v.customRules[name]; found {
return rule
}
if rule, found := v.predefinedRules[name]; found {
return rule
}
return rules.DefaultRule{}
}
// getErrorMessages converts validation error keys to user-friendly messages, if available.
func (v *Validator) getErrorMessages(fieldName string, errs []string) (messages []string) {
if len(errs) == 0 {
return []string{}
}
opts := map[string]any{
"Name": cases.Title(language.English).String(fieldName),
}
if len(errs) >= 2 {
opts["O1"] = errs[1]
}
if len(errs) >= 3 {
opts["O2"] = errs[2]
}
buf := bytes.Buffer{}
msg, ok := v.messages[errs[0]]
if fieldMsg, hasFieldMsg := v.fieldMessages[fmt.Sprintf("%s.%s", fieldName, errs[0])]; hasFieldMsg {
msg = fieldMsg
ok = true
}
if ok && len(msg) > 0 {
if tpl := template.New(fieldName); tpl != nil {
if t, err := template.New(fieldName).Parse(msg); err == nil && t.Execute(&buf, opts) == nil {
messages = append(messages, buf.String())
}
}
}
return
}
// isFieldNullable checks if a field is nullable and if its value is nil or considered null based on helper functions.
func (v *Validator) isFieldNullable(tag string, value interface{}) bool {
return strings.Contains(tag, "nullable") && (value == nil || helper.IsNull(value))
}
// validateRequiredField checks if a field is required and validates it. If validation fails, it returns an error message.
func (v *Validator) validateRequiredField(fieldName string, value interface{}, tag string) string {
if strings.Contains(tag, "required") {
if errs := (rules.RequiredRule{}).Validate(value, nil); len(errs) > 0 {
if messages := v.getErrorMessages(fieldName, errs); len(messages) > 0 {
return messages[0]
}
}
}
return ""
}
// applyRule applies a validation rule to a field value and returns any error messages generated by the rule.
func (v *Validator) applyRule(fieldName, rawRule string, value interface{}) []string {
split := strings.Split(rawRule, ":")
ruleName := split[0]
var ruleOption interface{}
if len(split) == 2 {
ruleOption = split[1]
}
rule := v.getRule(ruleName)
errs := rule.Validate(value, ruleOption)
return v.getErrorMessages(fieldName, errs)
}
// Validate validates the input struct based on the defined rules and returns a map of errors.
func (v *Validator) Validate(input interface{}) (map[string][]string, error) {
if !helper.IsStruct(input) {
return map[string][]string{}, ErrInvalidInput
}
result := map[string][]string{}
value := reflect.ValueOf(input)
for i := 0; i < value.NumField(); i++ {
var fieldValue any = nil
fieldName := strings.ToLower(value.Type().Field(i).Name)
fieldTag := value.Type().Field(i).Tag.Get("valid")
fieldRules := strings.Split(fieldTag, "|")
if value.Field(i).Kind() == reflect.Struct && value.Field(i).Type().Name() == "Time" {
fieldValue = value.Field(i)
}
if value.Field(i).CanInterface() {
fieldValue = value.Field(i).Interface()
}
if v.isFieldNullable(fieldTag, fieldValue) {
continue
}
if err := v.validateRequiredField(fieldName, fieldValue, fieldTag); err != "" {
result[fieldName] = []string{err}
continue
}
for _, rawRule := range fieldRules {
if _, ok := result[fieldName]; ok && v.failFast {
continue
}
if errs := v.applyRule(fieldName, rawRule, fieldValue); len(errs) > 0 {
result[fieldName] = append(result[fieldName], errs...)
}
}
if helper.IsStruct(fieldValue) {
if errs, _ := v.Validate(fieldValue); len(errs) > 0 {
for deepField := range errs {
result[fmt.Sprintf("%s.%s", fieldName, deepField)] = errs[deepField]
}
}
}
}
return result, nil
}
// AppendRule can be used to store / add a custom rule. The rule needs to implement the rules.Rule interface
func (v *Validator) AppendRule(rule rules.Rule) *Validator {
v.customRules[rule.Name()] = rule
return v
}
// SetMessage will override the default message for the given ruleErr like "no-string", etc.
func (v *Validator) SetMessage(ruleErr, message string) *Validator {
v.messages[ruleErr] = message
return v
}
// SetMessage does the same as SetMessage but for specific field on the struct.
func (v *Validator) SetFieldMessage(field, rule, message string) *Validator {
v.fieldMessages[fmt.Sprintf("%s.%s", field, rule)] = message
return v
}
// SetMessages can be used for translations and replaces the map of messages with the given map
func (v *Validator) SetMessages(messages map[string]string) *Validator {
v.messages = messages
return v
}
// SetFailFast will set the failFast flag. Upcoming rules will be skipped per field if we have at least one error in the list
// This essentially shrinks the length of error messages to a maximum of 1
func (v *Validator) SetFailFast(failFast bool) *Validator {
v.failFast = failFast
return v
}
// NewValidator constructs a new Validator with predefined rules and default messages.
func NewValidator() *Validator {
messages := map[string]string{
"between": "must be between {{.O1}} and {{.O2}}",
"between-invalid-value": "the given value cannot be used for a range check",
"no-bool": "is not a bool",
"default": "",
"email": "is not a email",
"json": "is not a valid JSON Object",
"jwt": "is not a valid JSON Web Token",
"min": "must be greater than or equal to {{.O1}}",
"max": "must be less than or equal to {{.O1}}",
"no-numeric": "is not a number",
"no-pointer": "is not a pointer",
"required": "is required",
"no-string": "is not a string",
"no-int": "is not a integer",
"int-wrong-size": "value needs to be {{.O1}} bit",
"no-uint": "is not a unsigned integer",
"uint-wrong-size": "value needs to be {{.O1}} bit",
"no-float": "is not a float",
"no-time": "is not a valid date",
"time-not-today": "has to be today",
"time-not-yesterday": "has to be yesterday",
"time-not-in-future": "needs to be in the future",
"time-not-in-past": "needs to be in the past",
"float-wrong-size": "value needs to be {{.O1}} bit",
"not-same-day": "Day is not {{.O1}}",
"not-same-month": "Month is not {{.O1}}",
"not-same-year": "Year is not {{.O1}}",
}
predefinedRules := map[string]rules.Rule{}
ruleBucket := []rules.Rule{
rules.BetweenRule{},
rules.BoolRule{},
rules.DefaultRule{},
rules.EmailRule{},
rules.JSONRule{},
rules.JWTRule{},
rules.MaxRule{},
rules.MinRule{},
rules.NumericRule{},
rules.PointerRule{},
rules.RequiredRule{},
rules.StringRule{},
rules.IntRule{},
rules.UintRule{},
rules.FloatRule{},
rules.TimeRule{},
rules.DateRule{},
}
for _, rule := range ruleBucket {
predefinedRules[rule.Name()] = rule
}
return &Validator{
messages: messages,
fieldMessages: map[string]string{},
customRules: map[string]rules.Rule{},
predefinedRules: predefinedRules,
}
}