-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalidation.go
184 lines (148 loc) · 4.88 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
package validation
import (
"fmt"
"reflect"
"strings"
"github.com/spf13/cast"
"github.com/thoas/go-funk"
"github.com/behzadsh/go.validator/bag"
"github.com/behzadsh/go.validator/rules"
"github.com/behzadsh/go.validator/translation"
)
type ruleIndicator string
// RulesMap is a custom type for a map of rules for field selectors.
type RulesMap map[string][]string
func (r ruleIndicator) load(locale string) rules.Rule {
name, params := r.parseRuleParams()
rule, ok := registry[name]
if !ok || rule == nil {
panic(fmt.Errorf("rule %s is not registered", name))
}
if ruleWithParams, ok := rule.(rules.RuleWithParams); ok {
paramNum := len(params)
minRequiredParams := ruleWithParams.MinRequiredParams()
if paramNum < minRequiredParams {
panic(fmt.Errorf("rule %s need at least %d parameter, got %d", name, minRequiredParams, paramNum))
}
ruleWithParams.AddParams(params)
}
if translatableRule, ok := rule.(translation.TranslatableRule); ok {
translatableRule.AddLocale(locale)
translatableRule.AddTranslationFunction(translation.GetDefaultTranslatorFunc())
}
return rule
}
func (r ruleIndicator) parseRuleParams() (string, []string) {
parts := strings.SplitN(string(r), ":", 2)
if len(parts) == 1 {
return parts[0], nil
}
return parts[0], cast.ToStringSlice(funk.Map(strings.Split(parts[1], ","), func(s string) string {
return strings.TrimSpace(s)
}))
}
// ValidateMap validate the given input map with given rules map.
func ValidateMap(input map[string]any, rulesMap RulesMap, locale ...string) Result {
currentLocale := defaultLocale
if len(locale) > 0 {
currentLocale = locale[0]
}
inputBag := bag.InputBag(input)
return doValidation(inputBag, rulesMap, currentLocale)
}
// ValidateMapSlice validates the given slice of maps with given rules map.
func ValidateMapSlice(input []map[string]any, rulesMap RulesMap, locale ...string) Result {
currentLocale := defaultLocale
if len(locale) > 0 {
currentLocale = locale[0]
}
result := NewResult()
for i, m := range input {
inputBag := bag.InputBag(m)
tmpResult := doValidation(inputBag, rulesMap, currentLocale)
for key, messages := range tmpResult.Errors {
result.addError(fmt.Sprintf("%d.%s", i, key), messages...)
}
}
return result
}
// ValidateStruct validates the given struct with given rules map.
func ValidateStruct(input any, rulesMap RulesMap, locale ...string) Result {
currentLocale := defaultLocale
if len(locale) > 0 {
currentLocale = locale[0]
}
v := reflect.ValueOf(input)
if v.Kind() != reflect.Struct && !(v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct) {
panic("validation.ValidateStruct only support struct or a pointer to a struct as first parameter")
}
inputBag := bag.NewInputBagFromStruct(input)
return doValidation(inputBag, rulesMap, currentLocale)
}
// ValidateStructSlice validates the given slice of struct with given rules map.
func ValidateStructSlice(input []any, rulesMap RulesMap, locale ...string) Result {
currentLocale := defaultLocale
if len(locale) > 0 {
currentLocale = locale[0]
}
result := NewResult()
for i, strct := range input {
tmpResult := ValidateStruct(strct, rulesMap, currentLocale)
for key, messages := range tmpResult.Errors {
result.addError(fmt.Sprintf("%d.%s", i, key), messages...)
}
}
return result
}
// Validate validate the given input with given validation rules.
func Validate(input any, ruleSlice []string, locale ...string) Result {
currentLocale := defaultLocale
if len(locale) > 0 {
currentLocale = locale[0]
}
return doValidation(bag.InputBag{"variable": input}, RulesMap{"variable": ruleSlice}, currentLocale)
}
func doValidation(inputBag bag.InputBag, rulesMap RulesMap, locale string) Result {
explicitRules := make(RulesMap)
for fieldSelector, fieldRules := range rulesMap {
for _, explicitFieldSelector := range normalizeFieldSelector(fieldSelector, inputBag) {
explicitRules[explicitFieldSelector] = fieldRules
}
}
result := NewResult()
for selector, selectorRules := range explicitRules {
val, _ := inputBag.Get(selector)
for _, ruleStr := range selectorRules {
ruleName := ruleIndicator(ruleStr)
rule := ruleName.load(locale)
ruleResult := rule.Validate(selector, val, inputBag)
if ruleResult.Failed() {
result.addError(selector, ruleResult.Message())
if stopOnFirstFailure {
break
}
}
}
}
return result
}
func normalizeFieldSelector(selector string, input bag.InputBag) []string {
if !strings.Contains(selector, ".*") {
return []string{selector}
}
parts := strings.SplitN(selector, ".*", 2)
total := 0
val, ok := input.Get(parts[0])
if ok {
temp, err := cast.ToSliceE(val)
if err == nil {
total = len(temp)
}
}
var explicitSelectors []string
for i := 0; i < total; i++ {
key := fmt.Sprintf("%s.%d%s", parts[0], i, parts[1])
explicitSelectors = append(explicitSelectors, normalizeFieldSelector(key, input)...)
}
return explicitSelectors
}