-
Notifications
You must be signed in to change notification settings - Fork 2
/
string_validator.go
247 lines (202 loc) · 5.35 KB
/
string_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
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
package validator
import (
"context"
"fmt"
"reflect"
"regexp"
"strings"
"unicode/utf8"
"github.com/go-courier/validator/errors"
"github.com/go-courier/validator/rules"
)
var (
TargetStringLength = "string length"
)
type StrLenMode int
const (
STR_LEN_MODE__LENGTH StrLenMode = iota
STR_LEN_MODE__RUNE_COUNT
)
var strLenModes = map[StrLenMode]func(s string) uint64{
STR_LEN_MODE__LENGTH: func(s string) uint64 {
return uint64(len(s))
},
STR_LEN_MODE__RUNE_COUNT: func(s string) uint64 {
return uint64(utf8.RuneCount([]byte(s)))
},
}
func ParseStrLenMode(s string) (StrLenMode, error) {
switch strings.ToLower(s) {
case "rune_count":
return STR_LEN_MODE__RUNE_COUNT, nil
case "length", "":
return STR_LEN_MODE__LENGTH, nil
default:
return STR_LEN_MODE__LENGTH, fmt.Errorf("unsupported string length mode")
}
}
func (m StrLenMode) String() string {
switch m {
case STR_LEN_MODE__RUNE_COUNT:
return "rune_count"
default:
return "length"
}
}
// @string{VALUE_1,VALUE_2,VALUE_3}
// @string/regexp/
// @string<StrLenMode>[from,to]
// @string<StrLenMode>[length]
//
// aliases
// * char as string<rune_count>
/*
Validator for string
Rules:
ranges
@string[min,max]
@string[length]
@string[1,10] // string length should large or equal than 1 and less or equal than 10
@string[1,] // string length should large or equal than 1 and less than the maxinum of int32
@string[,1] // string length should less than 1 and large or equal than 0
@string[10] // string length should be equal 10
enumeration
@string{A,B,C} // should one of these values
regexp
@string/\w+/ // string values should match \w+
since we use / as wrapper for regexp, we need to use \ to escape /
length mode in parameter
@string<length> // use string length directly
@string<rune_count> // use rune count as string length
composes
@string<>[1,]
aliases:
@char = @string<rune_count>
*/
type StringValidator struct {
Enums map[string]string
Pattern *regexp.Regexp
LenMode StrLenMode
MinLength uint64
MaxLength *uint64
}
func init() {
ValidatorMgrDefault.Register(&StringValidator{})
}
func (StringValidator) Names() []string {
return []string{"string", "char"}
}
var typString = reflect.TypeOf("")
func (validator *StringValidator) Validate(v interface{}) error {
rv, ok := v.(reflect.Value)
if !ok {
rv = reflect.ValueOf(v)
}
if !rv.Type().ConvertibleTo(typString) {
return errors.NewUnsupportedTypeError(rv.Type().String(), validator.String())
}
s := rv.Convert(typString).String()
if validator.Enums != nil {
if _, ok := validator.Enums[s]; !ok {
values := make([]interface{}, 0)
for _, v := range validator.Enums {
values = append(values, v)
}
return &errors.NotInEnumError{
Target: "string value",
Current: v,
Enums: values,
}
}
return nil
}
if validator.Pattern != nil {
if !validator.Pattern.MatchString(s) {
return &errors.NotMatchError{
Target: TargetStringLength,
Pattern: validator.Pattern,
Current: v,
}
}
return nil
}
strLen := strLenModes[validator.LenMode](s)
if strLen < validator.MinLength {
return &errors.OutOfRangeError{
Target: TargetStringLength,
Current: strLen,
Minimum: validator.MinLength,
}
}
if validator.MaxLength != nil && strLen > *validator.MaxLength {
return &errors.OutOfRangeError{
Target: TargetStringLength,
Current: strLen,
Maximum: validator.MaxLength,
}
}
return nil
}
func (StringValidator) New(ctx context.Context, rule *Rule) (Validator, error) {
validator := &StringValidator{}
if rule.ExclusiveLeft || rule.ExclusiveRight {
return nil, errors.NewSyntaxError("range mark of %s should not be `(` or `)`", validator.Names()[0])
}
if rule.Params != nil {
if len(rule.Params) != 1 {
return nil, fmt.Errorf("string should only 1 parameter, but got %d", len(rule.Params))
}
lenMode, err := ParseStrLenMode(string(rule.Params[0].Bytes()))
if err != nil {
return nil, err
}
validator.LenMode = lenMode
} else if rule.Name == "char" {
validator.LenMode = STR_LEN_MODE__RUNE_COUNT
}
if rule.Pattern != nil {
validator.Pattern = rule.Pattern
return validator, validator.TypeCheck(rule)
}
ruleValues := rule.ComputedValues()
if ruleValues != nil {
validator.Enums = map[string]string{}
for _, v := range ruleValues {
str := string(v.Bytes())
validator.Enums[str] = str
}
}
if rule.Range != nil {
min, max, err := UintRange(fmt.Sprintf("%s of string", validator.LenMode), 64, rule.Range...)
if err != nil {
return nil, err
}
validator.MinLength = min
validator.MaxLength = max
}
return validator, validator.TypeCheck(rule)
}
func (validator *StringValidator) TypeCheck(rule *Rule) error {
if rule.Type.Kind() == reflect.String {
return nil
}
return errors.NewUnsupportedTypeError(rule.String(), validator.String())
}
func (validator *StringValidator) String() string {
rule := rules.NewRule(validator.Names()[0])
if validator.Enums != nil {
ruleValues := make([]*rules.RuleLit, 0)
for _, e := range validator.Enums {
ruleValues = append(ruleValues, rules.NewRuleLit([]byte(e)))
}
rule.ValueMatrix = [][]*rules.RuleLit{ruleValues}
}
rule.Params = []rules.RuleNode{
rules.NewRuleLit([]byte(validator.LenMode.String())),
}
if validator.Pattern != nil {
rule.Pattern = validator.Pattern
}
rule.Range = RangeFromUint(validator.MinLength, validator.MaxLength)
return string(rule.Bytes())
}