-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalidator.go
70 lines (63 loc) · 1.47 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
package validator
import (
"reflect"
"strings"
)
type Field struct {
Name string
Value reflect.Value
Tag string
}
func Validate(s interface{}) (bool, string) {
fields := getFieldsFromStruct(s)
for _, field := range fields {
ok, message := validateField(field)
if !ok {
return ok, message
}
}
return true, ""
}
func validateField(field Field) (bool, string) {
rules := strings.Split(field.Tag, defaultTagSeperator)
for _, rule := range rules {
if strings.Contains(rule, "=") {
parseRule := strings.Split(rule, "=")
if mapRulesToFuncs[parseRule[0]] == nil {
continue
}
ok, message := mapRulesToFuncs[parseRule[0]](field, parseRule[1])
if !ok {
return ok, message
}
} else {
if mapRulesToFuncs[rule] == nil {
continue
}
ok, message := mapRulesToFuncs[rule](field, "")
if !ok {
return ok, message
}
}
}
return true, ""
}
func getFieldsFromStruct(s interface{}) []Field {
var fields []Field
fieldCount := reflect.ValueOf(s).Elem().NumField()
for i := 0; i < fieldCount; i++ {
field := reflect.TypeOf(s).Elem().Field(i)
tag := field.Tag.Get(defaultTagName)
fieldValue := reflect.ValueOf(s).Elem().Field(i)
newField := Field{
Name: field.Name,
Value: fieldValue,
Tag: tag,
}
fields = append(fields, newField)
}
return fields
}
func AddCustomValidation(validationName string, validationFunc func(field Field, value string) (bool, string)) {
mapRulesToFuncs[validationName] = validationFunc
}