This repository has been archived by the owner on Jul 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
default.go
86 lines (64 loc) · 1.43 KB
/
default.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
package validator
import (
"reflect"
"cyberpull.com/go-cyb/errors"
)
func Validate(data any, info ...*Validation) (err error) {
rValue := reflect.ValueOf(data)
rType := rValue.Type()
if rType.Kind() == reflect.Pointer {
rValue = rValue.Elem()
}
rKind := rType.Kind()
if rKind == reflect.Struct {
err = validateStruct(rValue)
return
}
if len(info) == 0 {
info = append(info, &Validation{})
}
switch rKind {
case reflect.String:
err = validateString(rValue.String(), info[0])
case reflect.Bool:
err = validateBool(rValue.Bool(), info[0])
}
return
}
func validateStruct(data reflect.Value) (err error) {
length := data.NumField()
for i := 0; i < length; i++ {
field := data.Field(i)
rType := data.Type().Field(i)
tag, ok := rType.Tag.Lookup("validator")
if !ok || tag == "" {
continue
}
info := parseValidationTag(rType, tag)
if err = Validate(field.Interface(), info); err != nil {
break
}
}
return
}
func validateString(data string, info *Validation) (err error) {
if info.Options.Required.Value && data == "" {
message := message(Required, info)
err = errors.New(message, 400)
return
}
if info.Options.Email.Value {
err = checkEmail(data, info)
if err != nil {
return
}
}
return
}
func validateBool(data bool, info *Validation) (err error) {
if info.Options.Required.Value && !data {
message := message(Required, info)
err = errors.New(message, 400)
}
return
}