-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.go
More file actions
53 lines (38 loc) · 886 Bytes
/
validator.go
File metadata and controls
53 lines (38 loc) · 886 Bytes
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
package gokit
import (
"reflect"
vengine "github.com/go-playground/validator/v10"
)
type Validator interface {
Validate(data any, rules ...any) (err error)
}
// ==========================
type validator struct {
core *vengine.Validate
}
func (v *validator) Validate(data any, rules ...any) (err error) {
rValue := reflect.ValueOf(data)
rType := rValue.Type()
rKind := rType.Kind()
if rKind == reflect.Pointer {
rValue = rValue.Elem()
}
value := rValue.Interface()
switch rKind {
case reflect.Struct:
return v.core.Struct(value)
default:
rule := oneOfAny[string]("", rules)
return v.core.Var(value, rule)
}
}
// ==========================
const defaultTagName string = "validate"
func NewValidator(tagName ...string) Validator {
tag := one(defaultTagName, tagName)
core := vengine.New()
core.SetTagName(tag)
return &validator{
core: core,
}
}