Repository navigation
Expand file tree
/
Copy pathvalidator.go
More file actions
344 lines (316 loc) · 8.77 KB
/
Copy pathvalidator.go
File metadata and controls
344 lines (316 loc) · 8.77 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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package validator
import (
"database/sql"
"fmt"
"strings"
)
// Validator holds the validation state.
type Validator struct {
input Input
rules Rules
customMsg Messages
errors ErrorBag
validated bool
bailMode bool
db *sql.DB
}
// WithDB sets the database connection used by the unique and exists rules.
func (v *Validator) WithDB(db *sql.DB) *Validator {
v.db = db
return v
}
// Make creates a new Validator. Validation runs lazily on first call to Fails or Errors.
func Make(input Input, rules Rules) *Validator {
return &Validator{
input: input,
rules: rules,
customMsg: make(Messages),
errors: make(ErrorBag),
}
}
// Messages sets custom error messages and returns the validator for chaining.
func (v *Validator) Messages(msgs Messages) *Validator {
v.customMsg = msgs
return v
}
// Bail stops validation after the first field that has an error.
func (v *Validator) Bail() *Validator {
v.bailMode = true
return v
}
// Fails reports whether any validation rule failed.
func (v *Validator) Fails() bool {
v.run()
return len(v.errors) > 0
}
// Passes reports whether all validation rules passed.
func (v *Validator) Passes() bool {
return !v.Fails()
}
// Errors returns all validation errors grouped by field.
func (v *Validator) Errors() ErrorBag {
v.run()
return v.errors
}
func (v *Validator) run() {
if v.validated {
return
}
v.validated = true
for field, ruleStr := range v.rules {
// ── Array wildcard (e.g. "tags.*") ────────────────────────────────────
if strings.HasSuffix(field, ".*") {
baseField := strings.TrimSuffix(field, ".*")
arr, ok := getNestedValue(v.input, baseField)
if !ok {
continue
}
items, ok := arr.([]any)
if !ok {
continue
}
for i, item := range items {
elemField := fmt.Sprintf("%s.%d", baseField, i)
v.validateSingle(elemField, item, ruleStr)
}
if v.bailMode && len(v.errors) > 0 {
return
}
continue
}
// ── Normal field validation ────────────────────────────────────────────
val, fieldPresent := getNestedValue(v.input, field)
v.validateSingle(field, val, ruleStr)
_ = fieldPresent
if v.bailMode && len(v.errors) > 0 {
return
}
}
}
// validateSingle runs all rules for a single field/value pair.
func (v *Validator) validateSingle(field string, val any, ruleStr string) {
parts := parseAndCache(ruleStr)
_, fieldPresent := getNestedValue(v.input, field)
hasRequired := false
isNullable := false
effectiveRequired := false
// Parse rule names first pass — detect nullable/required/flow conditions.
for _, p := range parts {
switch p.name {
case "required":
hasRequired = true
effectiveRequired = true
case "nullable":
isNullable = true
}
}
// ── Presence rules (present, filled) ──────────────────────────────────
for _, p := range parts {
if p.name == "present" {
if !fieldPresent {
msg := buildMsg("present", field, "")
v.errors[field] = append(v.errors[field], v.resolve(field, "present", msg))
}
continue
}
if p.name == "filled" {
if fieldPresent && isEmpty(val) {
msg := buildMsg("filled", field, "")
v.errors[field] = append(v.errors[field], v.resolve(field, "filled", msg))
return
}
continue
}
}
// ── Conditional required rules ────────────────────────────────────────
for _, p := range parts {
switch p.name {
case "required_if":
ps := splitParam(p.param)
if len(ps) >= 2 && fmt.Sprintf("%v", v.input[ps[0]]) == ps[1] {
effectiveRequired = true
}
case "required_unless":
ps := splitParam(p.param)
if len(ps) >= 2 && fmt.Sprintf("%v", v.input[ps[0]]) != ps[1] {
effectiveRequired = true
}
case "required_with":
for _, f := range splitParam(p.param) {
if !isEmpty(v.input[f]) {
effectiveRequired = true
break
}
}
case "required_without":
for _, f := range splitParam(p.param) {
if isEmpty(v.input[f]) {
effectiveRequired = true
break
}
}
case "required_with_all":
allPresent := true
for _, f := range splitParam(p.param) {
if isEmpty(v.input[f]) {
allPresent = false
break
}
}
if allPresent {
effectiveRequired = true
}
case "required_without_all":
allAbsent := true
for _, f := range splitParam(p.param) {
if !isEmpty(v.input[f]) {
allAbsent = false
break
}
}
if allAbsent {
effectiveRequired = true
}
}
}
// ── Handle nullable nil shortcut ──────────────────────────────────────
if isNullable && val == nil {
return
}
// ── Handle empty value ────────────────────────────────────────────────
if isEmpty(val) {
if effectiveRequired {
ruleName, msg := v.buildRequiredMsg(field, parts)
v.errors[field] = append(v.errors[field], v.resolve(field, ruleName, msg))
} else if !hasRequired {
// Optional field — skip further validation.
}
return
}
// ── Run check rules ───────────────────────────────────────────────────
fieldBail := hasBail(parts)
for _, p := range parts {
if isFlowRule(p.name) {
continue
}
if msg := v.check(p.name, p.param, field, val); msg != "" {
v.errors[field] = append(v.errors[field], v.resolve(field, p.name, msg))
if fieldBail {
return
}
break
}
}
}
// hasBail reports whether "bail" appears in a rule set.
func hasBail(parts []parsedRule) bool {
for _, p := range parts {
if p.name == "bail" {
return true
}
}
return false
}
// buildRequiredMsg finds the first triggered required-style rule and returns
// the rule name and its formatted message.
func (v *Validator) buildRequiredMsg(field string, parts []parsedRule) (ruleName, msg string) {
for _, p := range parts {
ps := splitParam(p.param)
switch p.name {
case "required":
return "required", buildMsg("required", field, p.param)
case "required_if":
if len(ps) >= 2 && fmt.Sprintf("%v", v.input[ps[0]]) == ps[1] {
return "required_if", buildMsgWith("required_if", map[string]string{
":field": humanize(field),
":other": humanize(ps[0]),
":value": ps[1],
})
}
case "required_unless":
if len(ps) >= 2 && fmt.Sprintf("%v", v.input[ps[0]]) != ps[1] {
return "required_unless", buildMsgWith("required_unless", map[string]string{
":field": humanize(field),
":other": humanize(ps[0]),
":value": ps[1],
})
}
case "required_with":
for _, f := range ps {
if !isEmpty(v.input[f]) {
return "required_with", buildMsgWith("required_with", map[string]string{
":field": humanize(field),
":other": humanize(f),
})
}
}
case "required_without":
for _, f := range ps {
if isEmpty(v.input[f]) {
return "required_without", buildMsgWith("required_without", map[string]string{
":field": humanize(field),
":other": humanize(f),
})
}
}
case "required_with_all":
allPresent := true
for _, f := range ps {
if isEmpty(v.input[f]) {
allPresent = false
break
}
}
if allPresent {
return "required_with_all", buildMsgWith("required_with_all", map[string]string{
":field": humanize(field),
":other": strings.Join(ps, ", "),
})
}
case "required_without_all":
allAbsent := true
for _, f := range ps {
if !isEmpty(v.input[f]) {
allAbsent = false
break
}
}
if allAbsent {
return "required_without_all", buildMsgWith("required_without_all", map[string]string{
":field": humanize(field),
":other": strings.Join(ps, ", "),
})
}
}
}
return "required", buildMsg("required", field, "")
}
// isFlowRule returns true for rules that are handled in validateSingle() and should not
// be passed to check().
func isFlowRule(name string) bool {
switch name {
case "nullable", "filled", "present", "bail",
"required_if", "required_unless",
"required_with", "required_without",
"required_with_all", "required_without_all":
return true
}
return false
}
func (v *Validator) resolve(field, rule, fallback string) string {
if msg, ok := v.customMsg[field+"."+rule]; ok {
return msg
}
if msg, ok := v.customMsg[rule]; ok {
return msg
}
return fallback
}
func parseRule(s string) (name, param string) {
parts := strings.SplitN(s, ":", 2)
name = strings.TrimSpace(parts[0])
if len(parts) == 2 {
param = strings.TrimSpace(parts[1])
}
return
}