-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.go
More file actions
54 lines (41 loc) · 842 Bytes
/
validator.go
File metadata and controls
54 lines (41 loc) · 842 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
54
package validator
import (
"errors"
"reflect"
)
var ErrRequired = errors.New("field required")
type Errors map[string]error
func (e Errors) Empty() bool {
return len(e) == 0
}
type (
Validator interface {
Valid() (bool, Errors)
}
Validation func() error
Validators map[string]Validation
)
func ByJSON(s interface{}, validators Validators) (bool, Errors) {
const tagName = "json"
var (
ok = true
errs = map[string]error{}
)
if s == nil || len(validators) == 0 {
return ok, errs
}
v := reflect.ValueOf(s)
if v.Kind() != reflect.Struct {
panic("value should be struct")
}
for i := 0; i < v.NumField(); i++ {
name := v.Type().Field(i).Tag.Get(tagName)
if valid, exists := validators[name]; exists {
if err := valid(); err != nil {
errs[name] = err
ok = false
}
}
}
return ok, errs
}