-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator.go
184 lines (173 loc) · 5.19 KB
/
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
package just
import (
"errors"
"reflect"
"regexp"
"strconv"
"strings"
)
/**
* Note: the validator relies on regular expression patterns of routing (bool, int, float, uuid).
*/
var (
rxValidRID = regexp.MustCompile("^" + patternParamRID + "$")
rxValidUuid = regexp.MustCompile("^" + patternParamUUID + "$")
rxValidFloat = regexp.MustCompile("^" + patternParamFloat + "$")
rxValidBoolean = regexp.MustCompile("^" + patternParamBoolean + "$")
rxValidInteger = regexp.MustCompile("^" + patternParamInteger + "$")
rxValidHex = regexp.MustCompile("^" + patternHex + "$")
)
// Structure validation errors.
type ValidationError struct {
Field string
Message string
}
// Validation error text.
func (e *ValidationError) Error() string {
if len(e.Field) > 0 && len(e.Message) > 0 {
return "Invalid \"" + e.Field + "\" - " + e.Message
}
return "Unknown"
}
func parseInstruction(instruction string) (string, string) {
if start := strings.IndexByte(instruction, '('); start > 0 {
if name := strings.TrimSpace(instruction[:start]); len(name) > 0 {
return name, strings.TrimSpace(strings.Trim(instruction[start:], "()"))
}
}
return strings.ToLower(strings.TrimSpace(instruction)), ""
}
func validationInt(i int64, instruction string) error {
if name, value := parseInstruction(instruction); len(name) > 0 && len(value) > 0 {
if name[0] == 'm' {
if m, err := strconv.ParseInt(value, 10, 64); err == nil {
if name == "min" {
if i < m {
return errors.New("value < min value")
}
} else if i > m {
return errors.New("value > max value")
}
}
}
}
return nil
}
func validationUnsignedInt(i uint64, instruction string) error {
if name, value := parseInstruction(instruction); len(name) > 0 && len(value) > 0 {
if name[0] == 'm' {
if m, err := strconv.ParseUint(value, 10, 64); err == nil {
if name == "min" {
if i < m {
return errors.New("value < min value")
}
} else if i > m {
return errors.New("value > max value")
}
}
}
}
return nil
}
func validationFloat(f float64, instruction string) error {
if name, value := parseInstruction(instruction); len(name) > 0 && len(value) > 0 {
if name[0] == 'm' {
if m, err := strconv.ParseFloat(value, 64); err == nil {
if name == "min" {
if f < m {
return errors.New("value < min value")
}
} else if f > m {
return errors.New("value > max value")
}
}
}
}
return nil
}
func validationString(str string, instruction string) error {
if name, value := parseInstruction(instruction); len(name) > 0 {
switch name {
case "boolean", "bool", "b":
if !rxValidBoolean.MatchString(str) {
return errors.New("is not boolean")
}
case "integer", "int", "i":
if !rxValidInteger.MatchString(str) {
return errors.New("is not integer")
}
case "float", "number", "f":
if !rxValidFloat.MatchString(str) {
return errors.New("is not float")
}
case "hex":
if !rxValidHex.MatchString(str) {
return errors.New("is not HEX")
}
case "uuid":
if !rxValidUuid.MatchString(str) {
return errors.New("is not UUID")
}
case "rid":
if !rxValidRID.MatchString(str) {
return errors.New("is not RID")
}
case "rgx", "regexp":
if rx, err := regexp.Compile(value); err == nil && rx != nil {
if !rx.MatchString(str) {
return errors.New("is not valid by regexp pattern " + value)
}
}
}
}
return nil
}
// Validation of the structure of the object according to the parameters within the tags.
func Validation(obj interface{}) []error {
var result []error = nil
if obj != nil {
if val := reflect.Indirect(reflect.ValueOf(obj)); val.IsValid() {
t := val.Type()
if k := t.Kind(); k != reflect.Array && k != reflect.Slice {
// Перебираем поля модели
for i := 0; i < t.NumField(); i++ {
if field := t.Field(i); len(field.Tag) > 0 && !field.Anonymous {
// Получаем инструкции валидации
if str, ok := field.Tag.Lookup("valid"); ok && len(str) > 0 {
for _, instruction := range strings.Split(str, ";") {
var err error = nil
// Убираем пробелы
instruction = strings.TrimSpace(instruction)
// Проводим анализ
fieldKind := field.Type.Kind()
switch fieldKind {
// Для целых чисел (min,max)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
err = validationInt(val.Field(i).Int(), instruction)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
err = validationUnsignedInt(val.Field(i).Uint(), instruction)
case reflect.Float32, reflect.Float64:
err = validationFloat(val.Field(i).Float(), instruction)
case reflect.String:
err = validationString(val.Field(i).String(), instruction)
default:
err = errors.New("unsupported validator")
}
if err != nil {
if result == nil {
result = make([]error, 0)
}
result = append(result, &ValidationError{
Field: field.Name,
Message: err.Error(),
})
}
}
}
}
}
}
}
}
return result
}